如何在 Java 字串中計算字元數?


宣告一個整數,將其初始化為 0,在 for 迴圈中為每個字元將其自增。

示例

即時演示

public class Sample {
   public static void main(String args[]) {

      String str = new String("Hi welcome to Tutorialspoint");
      int count = 0;
      for(int i = 0; i<str.length(); i++) {
         count++;
      }
      System.out.println("Number characters in the given string (including spaces) "+count);
   }
}

輸出

Number characters in the given string (including spaces) 28

更新於:20-2-2020

672 條評論

開啟您的 職業生涯

完成課程以獲得認證

開始學習
廣告