Home  >  Article  >  Backend Development  >  How to Verify the Presence of Special Characters in Strings in GoLang?

How to Verify the Presence of Special Characters in Strings in GoLang?

DDD
DDDOriginal
2024-11-01 10:05:30455browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn