Home > Backend Development > Golang > How to Check for Special Characters in Strings in GoLang?

How to Check for Special Characters in Strings in GoLang?

Patricia Arquette
Release: 2024-11-02 22:53:03
Original
237 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template