Home > Article > Backend Development > How to Check for Special Characters in Strings in GoLang?
Checking for Special Characters in Strings in GoLang
In GoLang, there are several ways to determine the presence of special characters within a string. One commonly utilized approach is leveraging the strings.ContainsAny function. For instance, the following code checks if the string contains any of the special characters "," or "|":
<code class="go">package main import "fmt" import "strings" func main() { fmt.Println(strings.ContainsAny("Hello World", ",|")) fmt.Println(strings.ContainsAny("Hello, World", ",|")) fmt.Println(strings.ContainsAny("Hello|World", ",|")) }</code>
Another method to verify if a string solely consists of ASCII characters is to utilize the strings.IndexFunc function. It takes a function that returns true for non-ASCII characters. For instance, the following code snippet:
<code class="go">package main import "fmt" import "strings" func main() { f := func(r rune) bool { return r < 'A' || r > 'z' } if strings.IndexFunc("HelloWorld", f) != -1 { fmt.Println("Found special char") } if strings.IndexFunc("Hello World", f) != -1 { fmt.Println("Found special char") } }</code>
This method is applicable in situations where you want to specifically check for non-ASCII characters. By employing any of the mentioned approaches, you can effectively ascertain whether a string contains special characters in GoLang.
The above is the detailed content of How to Check for Special Characters in Strings in GoLang?. For more information, please follow other related articles on the PHP Chinese website!