To check if a string contains only alphabets in Go, you can use a loop to iterate through each character in the string and check if it is an alphabet using Unicode values.
In this example,
str1
with a value of "HelloWorld"
.containsOnlyAlphabets
to true
, otherwise false
.package main
import (
"fmt"
"unicode"
)
func main() {
str1 := "HelloWorld"
containsOnlyAlphabets := true
for _, char := range str1 {
if !unicode.IsLetter(char) {
containsOnlyAlphabets = false
break
}
}
fmt.Println("String contains only alphabets:", containsOnlyAlphabets)
}
String contains only alphabets: true
In this example,
str2
with a value of "Hello123"
.containsOnlyAlphabets
to true
, otherwise false
.package main
import (
"fmt"
"unicode"
)
func main() {
str2 := "Hello123"
containsOnlyAlphabets := true
for _, char := range str2 {
if !unicode.IsLetter(char) {
containsOnlyAlphabets = false
break
}
}
fmt.Println("String contains only alphabets:", containsOnlyAlphabets)
}
String contains only alphabets: false
In this tutorial, we learned How to Check if String contains only Alphabets in Go language with well detailed examples.