Golang 检查给定字符是否存在于字符串中
在Go语言中,字符串与其他语言(如Java,C ++,Python等)不同。它是由变宽字符序列组成的,其中每个字符用一个或多个字节使用UTF-8编码来表示。在Go字符串中,允许使用给定的函数检查字符串中是否存在给定的字符。这些函数在字符串包中定义,因此必须在程序中导入字符串包才能访问这些函数:
1. 包含: 该函数用于检查给定字符串中是否存在给定字母。如果字母存在于给定字符串中,则返回true,否则返回false。
语法:
func Contains(str,chstr string) bool
在此,str是原始字符串,chstr是要检查的字符串。让我们通过以下示例来讨论这个概念:
示例:
// Go program to illustrate how to check
// the string is present or not in the
// specified string
package main
import (
"fmt"
"strings"
)
// Main function
func main() {
// Creating and initializing strings
str1 := "Welcome to Geeks for Geeks"
str2 := "Here! we learn about go strings"
fmt.Println("Original strings")
fmt.Println("String 1: ", str1)
fmt.Println("String 2: ", str2)
// Checking the string present or not
// Using Contains() function
res1 := strings.Contains(str1, "Geeks")
res2 := strings.Contains(str2, "GFG")
// Displaying the result
fmt.Println("\nResult 1: ", res1)
fmt.Println("Result 2: ", res2)
}
输出:
原始字符串
字符串1:欢迎来到Geeks的世界
字符串2:这里!我们了解关于Go字符串
结果1:真
结果2:假
2. ContainsAny: 该函数用于检查给定字符串中是否存在任何Unicode代码点。如果在给定字符串中有任何Unicode代码点,则此方法返回true,否则返回false。
语法:
func ContainsAny(str, charstr string) bool
在这里,str是原始字符串,charstr是Unicode代码点中的字符。让我们通过以下示例来讨论这个概念:
示例:
// Go program to illustrate how to check the
// string is present or not in the specified
// string
package main
import (
"fmt"
"strings"
)
// Main function
func main() {
// Creating and initializing strings
str1 := "Welcome to Geeks for Geeks"
str2 := "Here! we learn about go strings"
// Checking the string present or not
// Using ContainsAny() function
res1 := strings.ContainsAny(str1, "Geeks")
res2 := strings.ContainsAny(str2, "GFG")
res3 := strings.ContainsAny("GeeksforGeeks", "G & f")
res4 := strings.ContainsAny("GeeksforGeeks", "u | e")
res5 := strings.ContainsAny(" ", " ")
res6 := strings.ContainsAny("GeeksforGeeks", " ")
// Displaying the result
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)
}
输出:
结果1:真
结果2:假
结果3:真
结果4:真
结果5:真
结果6:假