Java 程序用于计算字符串中的字母
假设我们有以下字符串,其中有一些字母和数字。
String str = "9as78";
现在循环访问该字符串的长度,并使用 Character.isLetter() 方法。在此方法中,使用 charAt() 方法来检查字符串中的各个字符/数字。
for (int i = 0; i < str.length(); i++) {
if (Character.isLetter(str.charAt(i)))
count++;
}我们在上面设置了一个 count 变量,以获取 字符串 中字母的长度。
以下是完整示例。
示例
public class Demo {
public static void main(String []args) {
String str = "9as78";
int count = 0;
System.out.println("String: "+str);
for (int i = 0; i < str.length(); i++) {
if (Character.isLetter(str.charAt(i)))
count++;
}
System.out.println("Letters: "+count);
}
}输出
String: 9as78 Letters: 2
我们再看另一个示例。
示例
public class Demo {
public static void main(String []args) {
String str = "amit";
int count = 0;
System.out.println("String: "+str);
for (int i = 0; i < str.length(); i++) {
if (Character.isLetter(str.charAt(i)))
count++;
}
System.out.println("Letters: "+count);
}
}输出
String: amit Letters: 4
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP