Golang 中的 string.Contains 函数用于检查给定字符串中是否存在给定字母。如果给定的字符串中存在字母,则返回 true,否则返回 false。
用法:
func Contains(str, substr string) bool
这里, str 是原始字符串, substr 是您要检查的字符串。让我们借助一个例子来讨论这个概念:
范例1:
// Golang program to illustrate
// the strings.Contains() Function
package main
import (
"fmt"
"strings"
)
func main() {
// using the function
fmt.Println(strings.Contains("GeeksforGeeks", "for"))
fmt.Println(strings.Contains("A computer science portal", "science"))
}
输出:
true true
说明:在上面的例子中,我们检查了不同字符串中子字符串 ‘for’ 和 ‘science’ 的存在。由于 strings.Contains() 函数返回布尔值,因此在这两种情况下都返回 true。
范例2:以下示例说明了用户如何打印所需的结果而不是布尔输出:
// Golang program to illustrate
// the strings.Contains() Function
package main
import (
"fmt"
"strings"
)
func main() {
input:= "Golang"
str:= "This is a Golang program"
if strings.Contains(str, input) {
fmt.Println("Yes")
}
}
输出:
Yes
说明:在上面的例子中,我们取子串为‘input’,主串为‘str’。然后,我们检查主字符串中是否存在“Golang”。如果是这样,则返回“是”作为输出,如上所示。
相关用法
- Golang math.Lgamma()用法及代码示例
- Golang math.Float64bits()用法及代码示例
- Golang atomic.AddInt64()用法及代码示例
- Golang atomic.StoreInt64()用法及代码示例
- Golang reflect.FieldByIndex()用法及代码示例
- Golang bits.Sub()用法及代码示例
- Golang io.PipeWriter.CloseWithError()用法及代码示例
- Golang time.Round()用法及代码示例
- Golang reflect.AppendSlice()用法及代码示例
- Golang reflect.ChanOf()用法及代码示例
- Golang flag.Bool()用法及代码示例
- Golang time.Sleep()用法及代码示例
- Golang time.Time.Year()用法及代码示例
- Golang reflect.Indirect()用法及代码示例
- Golang reflect.CanAddr()用法及代码示例
- Golang reflect.CanInterface()用法及代码示例
- Golang reflect.CanSet()用法及代码示例
- Golang reflect.Cap()用法及代码示例
- Golang strings.ContainsRune()用法及代码示例
- Golang atomic.LoadInt64()用法及代码示例
- Golang reflect.Index()用法及代码示例
- Golang filepath.Abs()用法及代码示例
- Golang filepath.Base()用法及代码示例
- Golang bits.Sub32()用法及代码示例
注:本文由纯净天空筛选整理自preetikagupta8171大神的英文原创作品 string.Contains Function in Golang with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。