Golang 检查给定的字符是否存在于Golang字符串中
在Go语言中,字符串与其他语言如Java、C++、Python等不同。它是一个宽度可变的字符序列,每一个字符都由一个或多个使用UTF-8编码的字节表示。在Go字符串中,你可以使用给定的函数来检查字符串中存在的给定字符。这些函数是在strings包中定义的,所以你必须在你的程序中导入strings包以访问这些函数。
1.Contains: 该函数用于检查给定的字母是否存在于给定的字符串中。如果该字母存在于给定的字符串中,那么它将返回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)
}
输出
Original strings
String 1: Welcome to Geeks for Geeks
String 2: Here! we learn about go strings
Result 1: true
Result 2: false
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)
}
输出
Result 1: true
Result 2: false
Result 3: true
Result 4: true
Result 5: true
Result 6: false