How to check if a string contains only letters in Golang?
Checking if a string contains letters returns True if the string contains all letters, and False otherwise. Letters include any alphabetic character and excludes digits, punctuation, and other special characters.
Example using unicode.IsLetter function
package main
import (
"fmt"
"unicode"
)
func IsLetter(s string) bool {
for _, r := range s {
if !unicode.IsLetter(r) {
return false
}
}
return true
}
func main() {
fmt.Println(IsLetter("Golang")) // true
fmt.Println(IsLetter("Golang#54")) // false
}
Example using strings.Contains function
package main
import (
"fmt"
"strings"
)
const alpha = "abcdefghijklmnopqrstuvwxyz"
func alphaOnly(s string) bool {
for _, char := range s {
if !strings.Contains(alpha, strings.ToLower(string(char))) {
return false
}
}
return true
}
func main() {
fmt.Println(alphaOnly("Golang")) // true
fmt.Println(alphaOnly("Golang#54")) // false
}
Example using Regex
package main
import (
"fmt"
"regexp"
)
var IsLetter = regexp.MustCompile(`^[a-zA-Z]+$`).MatchString
func main() {
fmt.Println(IsLetter("Golang")) // true
fmt.Println(IsLetter("Golang#54")) // false
}
Regular expression is widely used for pattern matching. The regexp package provides support for regular expressions, which allow complex patterns to be found in strings. The regexp.MustCompile() function is used to create the regular expression and the MatchString() function returns a bool that indicates whether a pattern is matched by the string.