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