Java StringBuilder length()方法及示例

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()

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程