Golang 如何在字符串中检查指定的rune
在Go语言中,字符串与其他语言(如Java、C++、Python等)不同。它是一个可变宽度字符序列,其中每个字符都使用UTF-8编码表示为一个或多个字节。
在Go字符串中,您可以使用 ContainsRune() 函数检查给定字符串中是否包含指定的rune。如果给定字符串包含指定的rune,则此函数返回true,否则返回false。该函数在string包下定义,因此,在程序中访问ContainsRune函数,您必须导入string包。
语法:
func ContainsRune(str string, r rune) bool
其中,str是字符串,r是符文。此函数的返回类型为bool。让我们通过给定的例子来讨论这个概念:
例1:
// Go program to illustrate how to check
// the given string containing the rune
package main
import (
"fmt"
"strings"
)
func main() {
// Creating and initializing a string
// Using shorthand declaration
string_1 := "Welcome to GeeksforGeeks"
string_2 := "AppleAppleAppleAppleAppleApple"
string_3 := "%G%E%E%K%S"
// Creating and initializing rune
var r1, r2, r3 rune
r1 = 'R'
r2 = 'p'
r3 = 42
// Check the given string
// containing the rune
// Using ContainsRune function
res1 := strings.ContainsRune(string_1, r1)
res2 := strings.ContainsRune(string_2, r2)
res3 := strings.ContainsRune(string_3, r3)
// Display the results
fmt.Printf("String 1: %s , Rune 1: %q , Present or Not: %t",
string_1, r1, res1)
fmt.Printf("\nString 2: %s , Rune 2: %q , Present or Not: %t",
string_2, r2, res2)
fmt.Printf("\nString 3: %s , Rune 3: %q , Present or Not: %t",
string_3, r3, res3)
}
输出:
String 1: Welcome to GeeksforGeeks , Rune 1: 'R' , Present or Not: false
String 2: AppleAppleAppleAppleAppleApple , Rune 2: 'p' , Present or Not: true
String 3: %G%E%E%K%S , Rune 3: '*' , Present or Not: false
例2:
// Go program to illustrate how to check
// the given string containing the rune
package main
import (
"fmt"
"strings"
)
func main() {
// Creating and Checking the given
// rune present in the given string
// Using ContainsRune function
res1 := strings.ContainsRune("****Welcome, to,"+
" GeeksforGeeks****", 60)
res2 := strings.ContainsRune("Learning x how x to "+
"x trim x a x slice of bytes", 'r')
res3 := strings.ContainsRune("Geeks,for,Geeks, Geek", 'G')
// Display the results
fmt.Println("Final Result:")
fmt.Println("Result 1: ", res1)
fmt.Println("Result 2: ", res2)
fmt.Println("Result 3: ", res3)
}
输出:
Final Result:
Result 1: false
Result 2: true
Result 3: true