In GoLang, checking for special characters within a string requires specific methods. When encountering a string obtained from user input, ensuring its validity often necessitates verifying the absence of malicious or undesirable characters. This article explores two approaches to detect special characters in strings.
The strings.ContainsAny() function determines whether a string contains any character from a provided set of characters. To check for special characters, pass the string and a special character set to the function. For instance:
package main
import "strings"
func main() {
fmt.Println(strings.ContainsAny("Hello World", ",|")) // false
fmt.Println(strings.ContainsAny("Hello, World", ",|")) // true
fmt.Println(strings.ContainsAny("Hello|World", ",|")) // true
}
For checking if a string contains non-ASCII characters, strings.IndexFunc() proves useful. It returns the index of the first character that satisfies a provided function. Pass a function that checks if the character is outside the ASCII character range:
package main
import (
"fmt"
"strings"
)
func main() {
f := func(r rune) bool {
return r 'z'
}
if strings.IndexFunc("HelloWorld", f) != -1 {
fmt.Println("Found special char") // false
}
if strings.IndexFunc("Hello World", f) != -1 {
fmt.Println("Found special char") // true
}
}
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3