Java StringBuilder setLength()方法及实例

Java StringBuilder setLength()方法及实例

StringBuilder的 setLength(int newLength) 方法是用来 设置字符序列的长度等于newLength 的。如果作为参数传递的newLength小于旧的长度,则旧的长度被改变为newLength。 如果作为参数传递的newLength大于或等于旧的长度,则在旧序列的末尾添加空字符(’\u0000’),这样长度就成为新的长度参数。

语法

public void setLength(int newLength)

参数: 该方法接受一个参数 newLength ,它是一个整数类型的值,指的是你要设置的序列的新长度。
返回: 该方法不返回任何东西。
异常: 如果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)

参考文献: https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#setLength(int)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程