Saturday, August 24, 2013

Apache Commons StringUtils to manipulate Strings

Apache commons lang library has a stringutils class which has several useful methods which can be used for the most common string operations.
There are several methods in that class but here I will be going through some of the most useful methods.

Padding:
Often the String needs to be of a certain length with an option to pad some character to make the string of the required length.

String strNumber = “123″;
For left padding,
String strLeftPad = StringUtils.leftPad(strLeftPad, 10, “0″);
For Right Padding,
String strRightPad = StringUtils.rightPad(strLeftPad, 10, “Q”);
And similarly center,
String strCenterPad = StringUtils.center(“a”, 5, ‘y’)

Null/Blank checks:
Several times we write code similar to the below for null checks and blank checks.

if(strNumber!= null && strNumber.length() > 0){
}

That can be replaced with the isNotBlank method. If the String is not null and not empty or blank, then this method returns true else false.

boolean isEmpty = StringUtils.isNotBlank(strNumber);
Similarly there is method to check if the String is null or blank or empty.
boolean isEmpty = StringUtils.isBlank(strNumber);

defaultIfBlank and defaultIfEmpty are 2 very useful methods in this class.
defaultIfBlank returns either the passed in String, or if the String is whitespace, empty (“”) or null, the value of default String
defaultIfEmpty returns either the passed in String, or if the String is empty or null, the value of default String.

StringUtils.defaultIfEmpty(null, “defaultDue2Empty”)  = “defaultDue2Empty”
StringUtils.defaultIfEmpty(“”, “defaultDue2Empty”)    = “defaultDue2Empty”
StringUtils.defaultIfEmpty(” “, “defaultDue2Empty”)   = ” “
StringUtils.defaultIfEmpty(“bat”, “defaultDue2Empty”) = “bat”
StringUtils.defaultIfEmpty(“”, null)      = null

StringUtils.defaultIfBlank(null, “defaultDue2Blank”)  = “defaultDue2Blank”
StringUtils.defaultIfBlank(“”, “defaultDue2Blank”)    = “defaultDue2Blank”
StringUtils.defaultIfBlank(” “, “defaultDue2Blank”)   = “defaultDue2Blank”
StringUtils.defaultIfBlank(“bat”, “defaultDue2Blank”) = “bat”
StringUtils.defaultIfBlank(“”, null)      = null

Start/End String match:

The endsWithAny method checks if the String ends with any of the string in the provided String array. This method is case sensitive.

StringUtils.endsWithAny(“test.rtf”, new String[] {“docx”, “rtf”, “doc”}) = true
Similarly endsWithIgnoreCase is not case sensitive.
StringUtils. endsWithIgnoreCase (“test.RTF”, new String[] {“docx”, “rtf”, “doc”}) = true

startsWithAny method checks if the String starts with any of the String in array provided.
This method is case sensitive. Similarly startsWithIgnoreCase method does the same functionality except that it is not case sensitive.

StringUtils.startsWithAny(“C:/Chapter1/test.rtf”, new String[] { “C:/Chapter1″,”C:/Chapter2″, ” C:/Chapter3″}) = true;

StringUtils.startsWithIgnoreCase(“C:/CHAPTER1/test.rtf”, new String[] { “C:/Chapter1″,”C:/Chapter2″, ” C:/Chapter3″}) = true;

The left and right methods gets the left most and right most characters in the string.
public static String right(String str, int len)
public static String left(String str, int len)

where
len - the length of the required String

Reverse:

The reverse method provides functionality equivalent to that of StringBuilder.reverse().

This method reverses the String passed.

StringUtils.reverse(“bat”) = “tab”

String count:

countMatches method returns the number of times the char sequence passed in is available in the string.

StringUtils.countMatches(“I am learning commons string utils”, “ring”)  = 1

String Case:

swapCase reverses the case of the existing String.
Swaps the case of a String changing upper and title case to lower case, and lower case to upper case.
  • Upper case character converts to Lower case
  • Title case character converts to Lower case
  • Lower case character converts to Upper case
StringUtils.swapCase(“I am learning commons string utils”)  = “i AM LEARNING COMMONS STRING UTILS”

Capitalize method capitalize the 1st letter of the provided String.
StringUtils.capitalize(“mr”) = “Mr”

repeat method:
public static String repeat(String str, String separator, int repeat)
Repeat a String repeat times to form a new String, with a String separator injected each time.

StringUtils.repeat(“”, “t”, 3)    = “ttt”

String split:

There are some methods available in the StringUtils class which provides equivalent functionality of StringTokenizer.

splitByWholeSeparator method splits the string with the provided delimiter string and returns an array of the split Strings.

String s1 = “we are using apache commons lang library”;
String[] arraySplitStrings =  StringUtils.splitByWholeSeparator(s1, ” “);

for(int num = 0 ; num < arraySplitStrings.length;num++)
System.out.println(arraySplitStrings[num]);

Output:
we
are
using
apache
commons
lang
library

This method can also limit the maximum number of sub strings that can be created by splitting the string.

String[] arraySplitStrings =  StringUtils.splitByWholeSeparator(s1, ” “,3);
for(int num = 0 ; num < arraySplitStrings.length;num++)
System.out.println(arraySplitStrings[num]);

Output:
we
are
using apache commons lang library

These are some of the most useful methods in the Apache commons lang library which can save us lot of time in writing the string manipulations lot of times.

No comments:

Post a Comment