English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
No Go string, você pode usar a função fornecida para verificar se uma string contém um caractere específico. Essas funções são definidas na biblioteca de strings, portanto, você deve importar a biblioteca de strings no seu programa para acessar essas funções:
1.Contains:Esta função é usada para verificar se uma string contém um caractere específico. Se o caractere existir na string fornecida, ela retornará true, caso contrário, retornará false.
Sintaxe:
func Contains(str, chstr string) bool
aqui,str是原始字符串,而é a string original, enquantochstr
//é a string que você deseja verificar. Vamos discutir este conceito com um exemplo: //A string especificada package main import ( "fmt" "strings" ) func main() { //Criar e inicializar uma string str1 := "Welcome to w3codebox for w3codebox " str2 := "Here! we learn about go strings" fmt.Println("A string original") fmt.Println("String 1: ", str1) fmt.Println("String 2: ", str2) //verificar se uma string existe //Usar a função Contains() res1 := strings.Contains(str1, "w3codebox) res2 := strings.Contains(str2, "GFG") //Exibir o resultado fmt.Println("\nResult 1: ", res1) fmt.Println("Result 2: ", res2) }
Saída:
A string original String 1: Welcome to w3codebox for w3codebox String 2: Here! we learn about go strings Result 1: true Result 2: false
2. ContainsAny:Esta função é usada para verificar se existe qualquer caractere Unicode presente em charstr na string str. Se houver qualquer caractere Unicode presente em charstr na string str, este método retorna true, caso contrário, retorna false.
Sintaxe:
func ContainsAny(str, charstr string) bool
aqui,str é a string original,charstr é um caractere Unicode presente em chars. Vamos discutir este conceito com um exemplo:
//Se a string contém ou não uma substrig especificada package main import ( "fmt" "strings" ) func main() { //Criar e inicializar uma string str1 := "Welcome to Geeks for Geeks" str2 := "Here! we learn about go strings" //verificar se uma string existe //Usar a função ContainsAny() res1 := strings.ContainsAny(str1, "Geeks") res2 := strings.ContainsAny(str2, "GFG") res3 := strings.ContainsAny("w3codebox, "G & f") res4 := strings.ContainsAny("w3codebox, "u | e") res5 := strings.ContainsAny(" ", ") res6 := strings.ContainsAny("w3codebox, ") //Exibir o resultado 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) }
Saída:
Result 1: true Result 2: false Result 3: false Result 4: false Result 5: true Result 6: false