Golang 如何检查字符串中的指定符文

Golang 如何检查字符串中的指定符文

在Go语言中,字符串与其他语言如Java , C++ , Python等不同。它是一串宽度可变的字符,每一个字符都由一个或多个使用UTF-8编码的字节表示。

在Go字符串中,你可以使用 ContainsRune() 函数检查给定的字符串中是否包含指定的符文。如果给定的字符串中包含指定的符文,则该函数返回true;如果给定的字符串不包含指定的符文,则该函数返回false。它被定义在字符串包下,因此,你必须在你的程序中导入字符串包以访问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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程