📌  相关文章
📜  如何在Golang String中检查指定的符文?

📅  最后修改于: 2021-10-25 02:29:41             🧑  作者: Mango

在 Go 语言中,字符串不同于Java、C++、 Python等其他语言。它是一系列可变宽度字符,其中每个字符都由一个或多个使用 UTF-8 编码的字节表示。
在 Go字符串,您可以使用ContainsRune()函数检查给定字符串包含指定的符文。如果给定的字符串包含在其指定的符文,或该函数返回false如果给定的字符串不包含指定的符文此函数返回true。它定义在字符串包下,因此您必须在程序中导入字符串包才能访问 ContainsRune函数。

句法:

func ContainsRune(str string, r rune) bool

这里, str是字符串, r是 s 符文。该函数的返回类型是 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