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)
参考:
https://docs.oracle.com/javase/10/docs/api/java Java)