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.
Most Helpful This Week
How to check if a string contains a white space in Golang?
How to check if a string contains certain characters in Golang?
How to check if a string contains a substring in Golang?
How to trim leading and trailing white spaces of a string in Golang?
How to check string contains uppercase lowercase character in Golang?
How to check lowercase characters in a string in Golang?
How to remove special characters from a string in GoLang?
How to remove multiple spaces in a string in GoLang?
Strip all white spaces, tabs, newlines from a string
How to verify a string only contains letters, numbers, underscores, and dashes in Golang?