How to check if there is a special character in a string or if a character is a special character in GoLang

After reading the line from the input, I need to check if there is a special character in it

+5
source share
4 answers

I ended up doing something like this

alphabet := "abcdefghijklmnopqrstuvwxyz" alphabetSplit := strings.Split(alphabet, "") inputLetters := strings.Split(input, "") for index, value := range inputLetters { special:=1 for _, char :=range alphabetSplit{ if char == value { special = 0 break } } 

It may have something wrong, because since I used it for something specific, I had to edit it here.

-1
source

You can use .ContainsAny lines to see if a rune exists:

 package main import ( "fmt" "strings" ) func main() { fmt.Println(strings.ContainsAny("Hello World", ",|")) fmt.Println(strings.ContainsAny("Hello, World", ",|")) fmt.Println(strings.ContainsAny("Hello|World", ",|")) } 

Or, if you want to check if there are only ASCII characters, you can use .IndexFunc lines:

 package main import ( "fmt" "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") } } 
+7
source

Depending on your definition of a special character, the simplest solution is likely to make a for range loop on your line (which gives runes instead of bytes), and for each rune, check if it is on your list of allowed / forbidden runes.

See Strings, Bytes, Runes, and Symbols in Go for more information on the relationships between strings, bytes, and runes.

Playground Example

+3
source

You want to use the unicode package, which has a nice function for checking characters.

https://golang.org/pkg/unicode/#IsSymbol

 package main import ( "fmt" "unicode" ) func hasSymbol(str string) bool { for _, letter := range str { if unicode.IsSymbol(letter) { return true } } return false } func main() { var strs = []string { "A quick brown fox", "A+quick_brown<fox", } for _, str := range strs { if hasSymbol(str) { fmt.Printf("String '%v' contains symbols.\n", str) } else { fmt.Printf("String '%v' did not contain symbols.\n", str) } } } 

This will produce the following result:

 String 'A quick brown fox' did not contain symbols. String 'A+quick_brown<fox' contains symbols. 
-1
source

All Articles