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)
相關用法
- Java StringBuffer setLength()用法及代碼示例
- Java StringBuilder reverse()用法及代碼示例
- Java StringBuilder subSequence()用法及代碼示例
- Java StringBuilder replace()用法及代碼示例
- Java StringBuilder length()用法及代碼示例
- Java StringBuilder setCharAt()用法及代碼示例
- Java StringBuilder delete()用法及代碼示例
- Java StringBuilder deleteCharAt()用法及代碼示例
- Java StringBuilder getChars()用法及代碼示例
- Java StringBuilder charAt()用法及代碼示例
- Java StringBuilder capacity()用法及代碼示例
- Java StringBuilder codePointBefore()用法及代碼示例
- Java StringBuilder ensureCapacity()用法及代碼示例
- Java StringBuilder Class用法及代碼示例
- Java StringBuilder codePointAt()用法及代碼示例
注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 StringBuilder setLength() in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。