當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Guava Splitter omitEmptyStrings()用法及代碼示例


方法omitEmptyStrings()返回一個拆分器,該拆分器的行為與此拆分器相同,但會自動從結果中忽略空字符串。例如,Splitter.on(',').omitEmptyStrings().split(“,a ,,, b,c ,,”)返回僅包含[“a”,“b”,“c”]的可迭代項。

用法:

public Splitter omitEmptyStrings()

返回值:此方法返回具有所需配置的拆分器。


Note: If either trimResults option is also specified when creating a splitter, that splitter always trims results first before checking for emptiness. So, for example,

Splitter.on(‘:’).omitEmptyStrings().trimResults().split(“:::“)

returns an empty iterable.

以下示例說明了omitEmptyStrings()方法的用法方式:

範例1:

// Java code to show implementation of 
// omitEmptyStrings() 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 = "geeks,,  for,,,  geeks,, noida,,, classes"; 
        System.out.println("String with empty strings:\n"
                           + str); 
  
        // Using omitEmptyStrings() method. 
        // Two delimiters sometimes occur right next 
        // to each other. This means an empty entry. 
        // But often in splitting, we don't want 
        // to keep empty entries. 
        List<String> myList = Splitter.on(', '). 
         trimResults().omitEmptyStrings().splitToList(str); 
  
        System.out.println("\nString with empty"
                           + " strings removed:\n"
                           + myList); 
    } 
}
輸出:
String with empty strings:
geeks,,  for,,,  geeks,, noida,,, classes

String with empty strings removed:
[geeks, for, geeks, noida, classes]

範例2:

// Java code to show implementation of 
// omitEmptyStrings() 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 = "Hello..$.$ everyone..$& $ what's up..?"; 
        System.out.println("String with empty strings:\n"
                           + str); 
  
        // Using omitEmptyStrings() method. 
        // Two delimiters sometimes occur right next 
        // to each other. This means an empty entry. 
        // But often in splitting, we don't want 
        // to keep empty entries. 
        List<String> myList = Splitter.on('.'). 
            trimResults().omitEmptyStrings().splitToList(str); 
  
        System.out.println("\nString with empty"
                           + " strings removed:\n"
                           + myList); 
    } 
}
輸出:
String with empty strings:
Hello..$.$ everyone..$& $ what's up..?

String with empty strings removed:
[Hello, $, $ everyone, $& $ what's up, ?]


相關用法


注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 Splitter omitEmptyStrings() method | Guava | Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。