CodeGym /Java Blog /Toto sisi /字串 length() 方法
John Squirrels
等級 41
San Francisco

字串 length() 方法

在 Toto sisi 群組發布

字串的長度是多少?

「Java 中字串的長度等於其中的字元數。包括字母、數字、空格和其他特殊字元。”
例如,字串“嘿,終於到了夏天了!” 的長度。” 是 26。 字串 length() 方法 - 1

Java中如何求字串的長度?

Java 提供了一種簡單方便的方法來計算任何String的長度。話不多說,讓我們來看一個查找字串長度的範例。

例子

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

      String alphabetsWithSpaces = "A B C";
      String digitsWithSpaces = "1 2 3";
      String specialCharsWithSpaces = "! @ $";
      String allChars = "Z X      3 $$$ ^^^ * )(";
      String sentence = "Hey, it's finally summers!";

      System.out.println(alphabetsWithSpaces + " length = " + alphabetsWithSpaces.length());
      System.out.println(digitsWithSpaces + " length = " + digitsWithSpaces.length());
      System.out.println(specialCharsWithSpaces + " length = " + specialCharsWithSpaces.length());
      System.out.println(allChars + " length = " + allChars.length());
      System.out.println(sentence + " length = " + sentence.length());
    }
}

輸出

ABC 長度 = 5 1 2 3 長度 = 5 !@ $ length = 5 ZX 3 $$$ ^^^ * )( length = 23 嘿,終於到了夏天!length = 26

結論

現在您一定熟悉如何在 Java 中尋找字串長度了。但是,如果您仍然有任何歧義,請不要迴避測試它們。快樂學習!
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION