當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java StringBuffer setLength()用法及代碼示例


StringBuffer類的setLength(int newLength)方法是一種內置方法,用於將字符序列的長度設置為等於newLength。如果作為參數傳遞的newLength小於舊長度,則舊長度將更改為newLength。如果作為參數傳遞的newLength大於或等於舊長度,則在舊序列的末尾附加空字符(\ u0000),以便長度成為newLength參數。

用法:

public void setLength(int newLength)

參數:
此方法接受一個參數newLength,該參數是Integer類型的值,它表示要設置的新序列長度。
返回值:
此方法不返回任何內容。
異常:
如果newLength為負,則IndexOutOfBoundsException


以下程序說明了java.lang.StringBuffer.setLength()方法:
示例1:

// Java program to demonstrate 
// the setLength() Method. 
  
class GFG { 
  
    public static void main(String[] args) 
    { 
        // create a StringBuffer object 
        // with a String pass as parameter 
        StringBuffer str 
            = new StringBuffer("WelcomeGeeks"); 
  
        // print string 
        System.out.println("String length = "
                           + str.length() +  
                  " and contains = " + str); 
  
        // set length equal to 10 
        str.setLength(10); 
  
        // print string 
        System.out.println("After setLength() String = "
                           + str.toString()); 
    } 
}

輸出:

String length = 12 and contains = WelcomeGeeks
After setLength() String = WelcomeGee

示例2:

// Java program to demonstrate 
// the setLength() Method. 
  
class GFG { 
    public static void main(String[] args) 
    { 
  
        // create a StringBuffer object 
        // with a String pass as parameter 
        StringBuffer str 
            = new StringBuffer("Tony Stark will die"); 
  
        // print string 
        System.out.println("String length = "
                           + str.length() +  
        " and contains = \"" + str + "\""); 
  
        // set length equal to 25 
        str.setLength(25); 
  
        // print string 
        System.out.println("After setLength() String = \""
                           + str.toString() + "\""); 
    } 
}

輸出:

String length = 19 and contains = "Tony Stark will die"
After setLength() String = "Tony Stark will die      "

示例3:當傳遞負的新長度時:

// Java program to demonstrate 
// Exception thrown by the setLength() Method. 
  
class GFG { 
    public static void main(String[] args) 
    { 
  
        // create a StringBuffer object 
        // with a String pass as parameter 
        StringBuffer str 
            = new StringBuffer("Tony Stark"); 
  
        try { 
            // pass length -15 
            str.setLength(-15); 
        } 
        catch (Exception e) { 
  
            e.printStackTrace(); 
        } 
    } 
}

輸出:

java.lang.StringIndexOutOfBoundsException: String index out of range: -15
    at java.lang.AbstractStringBuffer.setLength(AbstractStringBuffer.java:207)
    at java.lang.StringBuffer.setLength(StringBuffer.java:76)
    at GFG.main(File.java:15)

參考文獻:



相關用法


注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 StringBuffer setLength() in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。