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
Sample program to create csv and write data
Constructors in Golang
Replace numbers by zero from string
How to create a photo gallery in Go?
How to handle HTTP Get response?
How to check if a map contains a key in Go?
How to use Ellipsis (...) in Golang?
How to reads and decodes JSON values from an input stream?
Example to handle GET and POST request in Golang
Example: Fields and FieldsFunc from BYTES Package