更改 Java 中 StringBuffer 对象的长度
setLength(int newLength) 方法用于更改 StringBuffer 对象的长度。它设置字符序列的长度。字符序列更新为一个新的字符序列,其长度由方法中作为参数传递的值确定。newLength 应大于或等于 0。
java.lang.StringBuffer(int newLength) 方法声明如下 −
public void setLength(int newLength)
让我们看一个示例程序,说明 setLength(int newLength) 方法的使用
示例
public class Example {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello World");
System.out.println(sb);
System.out.println("Original length : "+sb.length());
System.out.println("Original capacity : "+sb.capacity());
sb.setLength(5); // changing the length of the StringBuffer object
System.out.println();
System.out.println(sb);
System.out.println("New length : " +sb.length());
System.out.println("New capacity : " +sb.capacity());
}
}输出
Hello World Original length : 11 Original capacity : 27 Hello New length : 5 New capacity : 27
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP