How to check Character is alphabetic or not in Golang?| Code examples
- Admin
- Dec 31, 2023
- Golang-examples
Learn programs on how to check whether the character is alphabetic or not in the go language. These do use an if-else statement and a switch case statement.
Alphabetic characters
are characters English letters in lower and upper case. Special characters are not allowed.
Characters in go language represent the rune
data type that contains the ASCII
code value from 0 to 127.
Please have a look at the below golang features to have an understanding of this program better.
How to check Character/rune is an alphabet or not in Golang?
In the below program, the character is stored in the rune
data type.
rune
represents characters in the ASCII
code from 0 to 127. We have used the if-else statement to check lowercase alphabets from a to z and upper case alphabets from A to Z. Finally, print the character in an alphabet or not to the console.
package main
import (
"fmt"
)
func checkAlphaChar(charVariable rune) {
if (charVariable >= 'a' && charVariable <= 'z') || (charVariable >= 'A' && charVariable <= 'Z') {
fmt.Printf("%s is an alphabet\n", string(charVariable))
} else {
fmt.Printf("%s is not an alphabet\n", string(charVariable))
}
}
func main() {
checkAlphaChar('a')
checkAlphaChar('_')
checkAlphaChar('Z')
checkAlphaChar('*')
}
Output:
a is an alphabet
\_ is not an alphabet
Z is an alphabet
- is not an alphabet
How to Check alphabet is ASCII using a switch case statement in Golang?
In Golang, each character represents an ASCII code from 0 to 127. ASCII values for Lowercase alphabet values are 97 to 122 and upper case alphabets are from 65 to 90.
We have used a switch case statement to check ASCII for alphabet check.
package main
import (
"fmt"
)
func asciiAlphaCheck(r rune) {
switch {
case 97 <= r && r <= 122:
fmt.Printf("%s is an alphabet\n", string(r))
case 65 <= r && r <= 90:
fmt.Printf("%s is an alphabet\n", string(r))
default:
fmt.Printf("%s is not an alphabet\n", string(r))
}
}
func main() {
asciiAlphaCheck('c')
asciiAlphaCheck('|')
asciiAlphaCheck('d')
asciiAlphaCheck('$')
}
Output:
c is an alphabet
| is not an alphabet
d is an alphabet
$ is not an alphabet