更改 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
廣告