如何計算 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-Feb-2020

674 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始
廣告