Golang Example - Program to check Character is alphabetic or not


In this Example, You will learn programsĀ  how to check whether the character is alphabetic or not in go languageĀ  using if else statement and switch case statement

Ā  Ā  Ā Alphabetic characters are characters English letters in lower and upper case. Special characters are not allowed. Characters in go language are represented in rune data type which contains ASCII code value from 0 to 127.

Please have a look of below golang features to have an understanding of this program better

Example Golang program to check Character/rune is an alphabet or not

In the below program, the character is store in rune data type. rune represents characters in ASCII code from 0 to 127 We have used if else statement to check lowercase alphabets from a to z and upper case alphabets from A to Z Finally print the character is 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 is

a is an alphabet  
_ is not an alphabet  
Z is an alphabet  
* is not an alphabet  

Example Golang program to check ASCII alphabet using a switch case statementĀ 

In Golang, each character is represented in 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 is

c is an alphabet  
| is not an alphabet  
d is an alphabet  
$ is not an alphabet  

Similar Posts