Home > Article > Backend Development > How to Verify the Presence of Special Characters in Strings in GoLang?
Verifying the Presence of Special Characters in Strings in GoLang
Strings often contain special characters that may need to be checked for specific use cases. In GoLang, there are effective ways to perform these checks.
Detecting Special Characters in a String
To ascertain if a string contains any special character, utilize the strings.ContainsAny function. It requires two parameters: the input string and a string containing the special characters to search for. If any of these characters exist in the input string, the function returns true; otherwise, it returns false.
Example:
<code class="go">fmt.Println(strings.ContainsAny("Hello World", ",|")) // true fmt.Println(strings.ContainsAny("Hello, World", ",|")) // true fmt.Println(strings.ContainsAny("Hello|World", ",|")) // true</code>
Checking for Non-ASCII Characters
If you're interested in verifying if a string contains only ASCII characters, use the strings.IndexFunc function. It takes two parameters: the input string and a function that returns true if the rune is a non-ASCII character. If any non-ASCII characters are found, the function returns the index of the first occurrence; otherwise, it returns -1.
Example:
<code class="go">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>
The above is the detailed content of How to Verify the Presence of Special Characters in Strings in GoLang?. For more information, please follow other related articles on the PHP Chinese website!