当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。