Google Guava Splitter Example

Sometimes, Java standard library is not good at string manipulation. Google Guava is a library written by Google which provides some nice features. The following example shows how to use Google Guava Splitter’s Modifier methods. Before starting, you need to download Google Guava jar file first and add it to your project path.

Splitter.on("...") is a factory method which produces a splitter. A methods that is invoked on the splitter is called a Modifier. There are 4 modifier methods: trimResults(), omitEmptyStrings(), limit(int limit) and trimResults(CharMatcher trimmer).

1. Basic Guava splitter example

The first example splits a string using no modifiers.

package String;
 
import com.google.common.base.Splitter;
 
public class GuavaSplitterExample {
 
	public static void main(String[] args) {
 
		String str = "a,,b,     c,,,d";
 
		Iterable<String> result = Splitter.on(',')
			       .split(str);
 
		System.out.println("--start--");
		for(String s: result){
			System.out.println(s);
		}
		System.out.println("--end--");
	}
}

Result:

--start--
a

b
     c


d
--end--

2. Ignore empty strings

If you want to ignore the empty strings, we can use omitEmptyStrings() modifier.

String str = "a,,b,     c,,,d";
 
Iterable<String> result = Splitter.on(',')
       .omitEmptyStrings()
       .split(str);

Result:

--start--
a
b
     c
d
--end--

3. Trim each string in the result

If you want to trim each string in the result, i.e., remove leading and ending white spaces, you can use trimResults() method.

String str = "a,,b,     c,,,d";
 
Iterable<String> result = Splitter.on(',')
	       .trimResults()
	       .omitEmptyStrings()
	       .split(str);

Result:

--start--
a
b
c
d
--end--

4. Limit the number of times of splitting

If you want to split limited times for the string, you can put the limit # by using limit(n):

String str = "a,,b,     c,,,d";
 
Iterable<String> result = Splitter.on(',')
		       .trimResults()
		       .omitEmptyStrings()
		       .limit(3)
		       .split(str);

Result:

--start--
a
b
c,,,d
--end--

5. Trim more characters

Not only you can trim white spaces, you can use trimResults(CharMatcher trimmer) to trim other characters such as digits, upper case letter, lower case letter, etc. Check out all available trimmer here.

String str = "a,,b,c1,,,d2";
 
Iterable<String> result = Splitter.on(',')
	       .trimResults(CharMatcher.DIGIT)
	       .omitEmptyStrings()
	       .split(str);

Result:

--start--
a
b
c
d
--end--

3 thoughts on “Google Guava Splitter Example”

Leave a Comment