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


Java StringBuilder setLength()用法及代码示例


StringBuilder的setLength(int newLength)方法用于将字符序列的长度设置为等于newLength。对于每个索引k大于0且小于newLength。如果作为参数传递的newLength小于旧长度,则将旧长度更改为newLength;如果作为参数传递的newLength大于或等于旧长度,则将空字符('\ u0000')附加在旧序列的末尾,以便长度成为newLength参数。

用法:

public void setLength(int newLength)

参数:
此方法接受一个参数newLength,该参数是Integer类型的值,它表示要设置的新序列长度。
返回值:
此方法不返回任何内容。
异常:
如果newLength为负,则IndexOutOfBoundsException


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

// Java program to demonstrate 
// the setLength() 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 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 StringBuilder object 
        // with a String pass as parameter 
        StringBuilder str 
            = new StringBuilder("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 StringBuilder object 
        // with a String pass as parameter 
        StringBuilder str 
            = new StringBuilder("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.AbstractStringBuilder.setLength(AbstractStringBuilder.java:207)
    at java.lang.StringBuilder.setLength(StringBuilder.java:76)
    at GFG.main(File.java:15)

参考文献:



相关用法


注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 StringBuilder setLength() in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。