Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 516
Kipz Avatar asked Aug 12 '15 09:08

Kipz


1 Answers

You can use strings.ContainsAny 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 strings.IndexFunc:

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")
    }
}
like image 98
Joshua Avatar answered Oct 08 '22 18:10

Joshua