fixedLength(int length)方法返回一個分隔符,該分隔符將字符串分成給定長度的片段。例如,Splitter.fixedLength(2).split(“abcde”)返回包含[“ab”,“cd”,“e”]的可迭代。最後一塊可以小於長度,但永遠不會為空。
用法:
public static Splitter fixedLength(int length)
參數:該方法將長度作為參數,該參數是分割後所需的碎片長度。它是一個正整數。
返回值:此方法返回具有默認設置的拆分器,該拆分器可以拆分為固定大小的片段。
異常:如果length為零或負數,則此方法引發IllegalArgumentException。
範例1:
// Java code to show implementation of
// fixedLength(int length) method
// of Guava's Splitter Class
import com.google.common.base.Splitter;
import java.util.List;
class GFG {
// Driver's code
public static void main(String[] args)
{
// Creating a string variable
String str = "Delhi Noida Chandigarh";
// Initially setting length as 3
System.out.println("When Length is 3:");
// Using fixedLength(int length) method which
// returns a splitter that divides strings
// into pieces of the given length
Iterable<String> result = Splitter.fixedLength(3)
.trimResults()
.split(str);
for (String temp:result) {
System.out.println(temp);
}
// Setting length as 4
System.out.println("\n\nWhen Length is 4:");
// Using fixedLength(int length) method which
// returns a splitter that divides strings
// into pieces of the given length
Iterable<String> result1 = Splitter.fixedLength(4)
.trimResults()
.split(str);
for (String temp:result1) {
System.out.println(temp);
}
}
}
輸出:
When Length is 3: Del hi Noi da Cha ndi gar h When Length is 4: Delh i No ida Chan diga rh
範例2:顯示IllegalArgumentException
// Java code to show implementation of
// fixedLength(int length) method
// of Guava's Splitter Class
import com.google.common.base.Splitter;
import java.util.List;
class GFG {
// Driver's code
public static void main(String[] args)
{
try {
// Creating a string variable
String str = "GeeksforGeeks is best";
// Initially setting length as 0
// This should throw "IllegalArgumentException"
// as length is 0
System.out.println("When Length is 0:");
// Using fixedLength(int length) method which
// returns a splitter that divides strings
// into pieces of the given length
Iterable<String> result = Splitter.fixedLength(0)
.trimResults()
.split(str);
for (String temp:result) {
System.out.println(temp);
}
}
catch (Exception e) {
System.out.println("Exception:" + e);
}
}
}
輸出:
When Length is 0: Exception:java.lang.IllegalArgumentException: The length may not be less than 1
相關用法
- Java Guava Splitter limit()用法及代碼示例
- Java Guava Splitter splitToList()用法及代碼示例
- Java Guava Splitter trimResults()用法及代碼示例
- Java Guava Splitter omitEmptyStrings()用法及代碼示例
- Java Guava Doubles.min()用法及代碼示例
- Java Guava Shorts.max()用法及代碼示例
- Java Guava Floats.max()用法及代碼示例
- Java Guava Chars.min()用法及代碼示例
- Java Guava Doubles.max()用法及代碼示例
- Java Guava Chars.max()用法及代碼示例
- Java Guava Longs.max()用法及代碼示例
- Java Guava Floats.min()用法及代碼示例
- Java Guava Shorts.contains()用法及代碼示例
注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 Splitter fixedLength() method | Guava | Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。