📜  Java中的 StringBuilder setLength() 示例

📅  最后修改于: 2022-05-13 01:54:23.600000             🧑  作者: Mango

Java中的 StringBuilder setLength() 示例

StringBuilder 的setLength(int newLength)方法用于将字符序列的长度设置为等于 newLength 。对于大于 0 且小于 newLength 的每个索引 k。如果作为参数传递的 newLength 小于旧长度,则将旧长度更改为 newLength。如果作为参数传递的newLength 大于或等于旧长度,则在旧序列的结尾,以便长度成为 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)

参考:
https://docs.oracle.com/javase/10/docs/api/java Java)