check if a string contains only letters in Go
Code snippet on how to check if a string contains only letters in Go
s := "string"
var valid bool
valid = true
for _, c := range s {
if (c < 'a' || c > 'z') && (c < 'A' || c > 'Z') {
valid = false
break
}
}
This code uses a for loop to check all characters in the string variable s
. For every character c
that is found, it checks if the character is between a and z, or between A and Z. If any character is outside of this range, the boolean variable valid
is set to false. If the loop runs to completion, valid
will still be true. At the end, valid
will have the value true if all characters were between a and z, or A and Z, and false otherwise.