Monday, February 18, 2013

Guava - Strings - CharMatcher

Guava's CharMatcher is a nifty little utility class for matching characters in a String.  It also allows you to perform specific operations on those characters as well, like removing them, collapsing them, etc.  I'm not going to demonstrate everything that this class can do.  I'll just give a few examples that showcase how Guava can simplify your code.

First Example

Suppose you wanted to trim and collapse all the whitespace characters in the String "   hello   world   ".
Guava
String str = "   hello     world     ";

System.out.println("Original: '" + str + "'");
System.out.println("Guava: '" + CharMatcher.WHITESPACE.trimAndCollapseFrom(str, ' ') + "'");
Java
String str = "   hello     world     ";

System.out.println("Original: '" + str + "'");
System.out.println("Java: '" + str.trim().replaceAll("\\s\\s+", " ") + "'");
It should be noted that Java is returning two new String objects: one for the trim method and another for replaceAll.  Guava only returns one new String object.

The above example was derived from Guava's wiki page for CharMatcher.

Second Example

Suppose you wanted to find all of the characters that are in the range from 'a' to 'g' in the String"the quick brown fox jumps over the lazy dog"
Guava
String str = "the quick brown fox jumps over the lazy dog";

System.out.println("Original: '" + str + "'");
System.out.println("Guava: '" + CharMatcher.inRange('a', 'g').retainFrom(str) + "'");
Java
String str = "the quick brown fox jumps over the lazy dog";

System.out.println("Original: '" + str + "'");

Pattern pattern = Pattern.compile("[a-g]");
Matcher matcher = pattern.matcher(str);

System.out.print("Java: '");
while(matcher.find()) {
  System.out.print(matcher.group());
}
System.out.println("'");
As you can see here, the Java version requires a lot more work.

The above example was derived Aleksander Stensby's blog titled "Divinginto the Google Guava library (part 2)"  I also utilized TutorialsPoint article on Java's Regular Expression.

Third Example

Suppose you wanted to count the number of (lowercase) letters in a String.
Guava
String str = " 1a! b2@  c#3 ";

System.out.println("Guava: " + CharMatcher.JAVA_LETTER.countIn(str));
Java
String str = " 1a! b2@  c#3 ";
    
Pattern pattern = Pattern.compile("[a-z]");
Matcher matcher = pattern.matcher(str);

int count = 0;
while(matcher.find()) {
  count++;
}

System.out.println("Java: " + count);
The above example was derived from Sezin Karli's blog entry titled "google's guava library tutorial part 1 : fun with string-related stuff"  Again I used TutorialsPoint article on Regular Expression as reference.

No comments:

Post a Comment