如何在Golang中检查一个字符是否在字母表中
首先,使用fmt库中的内置函数isLetter()可以减少代码的行数。
另一种方法是使用ASCII值的概念,因为每个字符都有一个独特的ASCII值,利用它我们可以找出当前字符是否是字母。
大写字母和小写字母的范围如下-
大写字母 – 65至90
小写字母 – 97至122
如果字符的ASCII值位于上述范围之间,那么该字符就是一个字母。
在这个例子中,我们将使用fmt库中的内置函数isLetter()来检查字符是否是一个字母。
fmt库中的isLetter()的语法如下。该函数接受一个字符作为参数。
Func isLetter(r rune) bool
第2步 – 在字符串上运行一个for循环。
第3步 – 开始一个if条件,并在if条件中调用IsLetter()函数。
第4步 – 打印相应的结果。
package main
import (
// fmt package provides the function to print anything
"fmt"
// unicode function is providing isLetter function
"unicode"
)
func main() {
// declaring and initializing the variable using the shorthand method in Golang
characters := "A&j()K"
fmt.Println("Golang program to check the character is an alphabet or not using IsLetter() function present in the Unicode library.")
// running a for loop to check each character in the string is alphabet or not
for i := 0; i < len(characters); i++ {
// calling the Isletter() function and printing the result on the basis
// of return value of the function
if unicode.IsLetter(rune(characters[i])) {
fmt.Printf("%c is a character.\n", characters[i])
} else {
fmt.Printf("%c is not a character.\n", characters[i])
}
}
}
% go run tutorialpoint.go
Golang program to check whether the character is an alphabet or not using the IsLetter() function present in the Unicode library.
A is a character.
& is not a character.
j is a character.
( is not a character.
) is not a character.
K is a character.
在这个例子中,我们将使用ASCII字符范围来检查该字符是否为字母表。
比较将使用小写和大写字母的ASCII值范围进行,如以下语法所示。
if (characters[i] >= 65 && characters[i] <= 90) || (characters[i] >= 97 && characters[i] <= 122) { }
第2步 – 在字符串上运行一个for循环。
第3步 – 启动一个if条件,比较当前索引字符的ASCII值是否在65和90或97和122之间。
第4步 – 打印相应的结果。
package main
import (
// fmt package provides the function to print anything
"fmt"
)
func main() {
// declaring and initializing the variable using the shorthand method in Golang
characters := "A&j()K"
fmt.Println("Golang program to check whether the character is an alphabet or not using the concept of ASCII values.")
// running a for loop to check if each character in the string is alphabet or not
for i := 0; i < len(characters); i++ {
// checking that the ASCII value of the character is in between the range
// of uppercase or lowercase characters or not
if (characters[i] >= 65 && characters[i] <= 90) || (characters[i] >= 97 && characters[i] <= 122) {
fmt.Printf("%c is a character.\n", characters[i])
} else {
fmt.Printf("%c is not a character.\n", characters[i])
}
}
}
% go run tutorialpoint.go
Golang program to check whether the character is an alphabet or not using the concept of ASCII values.
A is a character.
& is not a character.
j is a character.
( is not a character.
) is not a character.
K is a character.
这就是检查字符是否为字母的两种方式。第一种方式在模块化和代码可重用性方面更适合。要了解更多关于go的知识,你可以探索这些教程。