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

更新於:31-May-2024

17K+ 檢視

開啟您的 職業<5>

完成課程獲取認證

開始學習
廣告
© . All rights reserved.