Java程序判断给定字符是否为字母
对于一个字符 "ch",编写一个Java程序来验证它是否在a和z之间(包括小写和大写)。如果是,则它是字母;否则不是。
字母是在书写语言(如英语)中用来表示特定发音的一组字母。
示例场景1
Input: character = 'e'; Output: Yes given character is an alphabet
示例场景2
Input: character = '4'; Output: No given character is not an alphabet
使用ASCII值
术语ASCII代表美国信息交换标准代码。每个英文字母都有一个与其关联的ASCII值。对于字母,大写字母的值范围为65到90,小写字母的值范围为97到122。
使用if-else语句,我们检查ASCII值是否在此范围内。如果是,则该字符被认为是字母。
示例
在这个例子中,我们使用ASCII值来判断给定的字符是否为字母。
public class AlphabetOrNot {
public static void main(String args[]){
char ch = 'G';
System.out.println("Given character:: " + ch);
// checking character is alphabet or not
if(((ch >= 'A' && ch <= 'Z')||ch >= 'a' && ch <= 'z') ){
System.out.println("Given character is an alphabet");
}else{
System.out.println("Given character is not an alphabet");
}
}
}
运行上述代码后,您将得到以下输出:
Given character:: G Given character is an alphabet
使用isLetter()方法
isLetter()是Character类的方法,用于确定特定字符是否为字母。此方法接受字符作为参数,如果字符参数是字母,则返回TRUE,否则返回FALSE。
示例
下面的Java程序演示了如何检查给定的字符是否为字母。
public class AlphabetOrNot {
public static void main(String args[]) {
char ch = 'n';
System.out.println("Given character:: " + ch);
// using isLetter() method
if (Character.isLetter(ch)) {
System.out.println("Given character is an alphabet");
} else {
System.out.println("Given character is not an alphabet");
}
}
}
执行此程序后,将给出以下结果:
Given character:: n Given character is an alphabet
使用正则表达式
Java中的正则表达式是特殊的字符序列,它可以帮助您使用模式中包含的专用语法查找其他字符或字符串集。
我们将此模式作为参数值传递给Java String类的matches()方法,只有当且仅当此模式与给定的正则表达式匹配时,该方法才会返回TRUE。
示例
在这个Java程序中,我们使用正则表达式来验证给定的字符是否为字母。
public class AlphabetOrNot {
public static void main(String args[]) {
char ch = '4';
System.out.println("Given character:: " + ch);
// using regular expression
if (String.valueOf(ch).matches("[A-Za-z]")) {
System.out.println("Given character is an alphabet");
} else {
System.out.println("Given character is not an alphabet");
}
}
}
运行此代码后,它将显示以下结果:
Given character:: 4 Given character is not an alphabet
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP