在Go字符串中,可以使用給定的函數(shù)檢查字符串中存在的給定字符。這些函數(shù)在字符串包下定義,因此您必須在程序中導(dǎo)入字符串包才能訪問(wèn)這些函數(shù):
1.Contains:此函數(shù)用于檢查給定字符串中是否存在給定字符。如果字符存在于給定的字符串中,則它將返回true,否則返回false。
語(yǔ)法:
func Contains(str, chstr string) bool
在這里,str是原始字符串,而chstr是您要檢查的字符串。讓我們借助示例來(lái)討論這個(gè)概念:
//字符串中是否存在
//指定的字符串
package main
import (
"fmt"
"strings"
)
func main() {
//創(chuàng)建和初始化字符串
str1 := "Welcome to Nhooo for Nhooo "
str2 := "Here! we learn about go strings"
fmt.Println("原來(lái)的字符串")
fmt.Println("String 1: ", str1)
fmt.Println("String 2: ", str2)
//檢查字符串是否存在
//使用Contains()函數(shù)
res1 := strings.Contains(str1, "Nhooo")
res2 := strings.Contains(str2, "GFG")
//顯示結(jié)果
fmt.Println("\nResult 1: ", res1)
fmt.Println("Result 2: ", res2)
}輸出:
原來(lái)的字符串 String 1: Welcome to Nhooo for Nhooo String 2: Here! we learn about go strings Result 1: true Result 2: false
2. ContainsAny:此函數(shù)用于檢查給定字符串(str)中是否存在 charstr 中的任何Unicode字符。如果給定字符串(str)中有 charstr 中的任何Unicode字符,則此方法返回true,否則返回false。
語(yǔ)法:
func ContainsAny(str, charstr string) bool
在這里,str 是原始字符串,charstr 是chars中的Unicode字符。讓我們借助示例來(lái)討論這個(gè)概念:
//字符串存在或不存在指定字串
package main
import (
"fmt"
"strings"
)
func main() {
//創(chuàng)建和初始化字符串
str1 := "Welcome to Geeks for Geeks"
str2 := "Here! we learn about go strings"
//檢查字符串是否存在
//使用ContainsAny()函數(shù)
res1 := strings.ContainsAny(str1, "Geeks")
res2 := strings.ContainsAny(str2, "GFG")
res3 := strings.ContainsAny("nhooo", "G & f")
res4 := strings.ContainsAny("nhooo", "u | e")
res5 := strings.ContainsAny(" ", " ")
res6 := strings.ContainsAny("nhooo", " ")
//顯示結(jié)果
fmt.Println("\nResult 1: ", res1)
fmt.Println("Result 2: ", res2)
fmt.Println("Result 3: ", res3)
fmt.Println("Result 4: ", res4)
fmt.Println("Result 5: ", res5)
fmt.Println("Result 6: ", res6)
}輸出:
Result 1: true Result 2: false Result 3: false Result 4: false Result 5: true Result 6: false