当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。