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