當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java StringBuilder length()用法及代碼示例


StringBuilder類的length()方法返回StringBuilder對象包含的字符數。此方法返回當前由StringBuilder對象表示的字符序列的長度。

用法:

public int length()

返回值:此方法返回StringBuilder對象包含的字符序列的長度。


下麵的程序演示StringBuilder類的length()方法:

範例1:

// Java program to demonstrate 
// the length() Method. 
  
class GFG { 
    public static void main(String[] args) 
    { 
  
        // create a StringBuilder object 
        // with a String pass as parameter 
        StringBuilder 
            str 
            = new StringBuilder("WelcomeGeeks"); 
  
        // print string 
        System.out.println("String = "
                           + str.toString()); 
  
        // get length of StringBuilder object 
        int length = str.length(); 
  
        // print length 
        System.out.println("length of String = "
                           + length); 
    } 
}
輸出:
String = WelcomeGeeks
length of String = 12

範例2:

// Java program to demonstrate 
// the length() Method. 
  
class GFG { 
    public static void main(String[] args) 
    { 
  
        // create a StringBuilder object 
        // with a String pass as parameter 
        StringBuilder 
            str 
            = new StringBuilder("India is Great"); 
  
        // print string 
        System.out.println("String = "
                           + str.toString()); 
  
        // get length of StringBuilder object 
        int length = str.length(); 
  
        // print length 
        System.out.println("length of String = "
                           + length); 
    } 
}
輸出:
String = India is Great
length of String = 14

參考:
https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#length()



相關用法


注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 StringBuilder length() in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。