📜  拆分器 omitEmptyStrings() 方法 |番石榴 |Java

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

拆分器 omitEmptyStrings() 方法 |番石榴 |Java

方法omitEmptyStrings()返回一个与此拆分器等效的拆分器,但会自动从结果中省略空字符串。例如,Splitter.on (', ').omitEmptyStrings().split(“, a,,, b, c,,”) 返回一个仅包含 [“a”, “b”, “c”] 的可迭代对象。

句法:

public Splitter omitEmptyStrings()

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

下面的例子说明了 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 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 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, ?]