|
Page 2 of 5 Playing with Strings
Any application irrespective of whether it is a Swing-, J2EE-, or J2ME-based one, has to work with strings. So although working with a string in Java is fairly simple, if you wish to modify and manipulate the string based on certain conditions, things don't stay that simple. You have to hunt for obscure methods in the various string-related classes and then somehow get them to work together to get you the desired result.
While there are some Lang methods that do overlap with methods present in J2SE,
in most cases one Lang method provides the functionality of many J2SE methods
from various classes, working together to get you the desired output.
The Lang component has many classes dedicated to string manipulation. We will now use a basic Java application to demonstrate some of the more useful classes and methods.
String manipulation is generally involved when your application takes input from a user and you either do not trust what the user will enter or the user might enter data in various formats but you only wish to work and store in one format.
Credit card number rules work somewhat like this, so if I tell you I have a MasterCard and the card number begins with 4, you'll know I am lying right away. Refer to Anatomy of Credit Card Numbers
As an example, you have a form with an input box for the user to enter a license key. You wish to allow a key in the format 1111-JAVA. The things you have to provide for are:
- Check for null and empty string.
- Ignore white spaces.
- The license key is case-sensitive.
- Split the key string using the - sign, and then check if the first part is all numeric and the second part contains characters only from the set of valid characters "J", "A", "V", "A".
- Both parts should have four characters.
- The fourth digit in the first part should be a "0".
Only if the key fulfills all these conditions do you want your application to go to the trouble of going to the database and checking if the key is a legitimate one.
Can you do all this without spending a fair amount of time browsing through the API documentation for the String, StringTokenizer, and other classes? I can't, so I will now try to manage the validation using the Lang component.
Listing 1. The checkLicenseKey() method
/**
* Check if the key is valid
* @param key license key value
* @return true if key is valid, false otherwise.
*/
public static boolean checkLicenseKey(String key){
//checks if empty or null
if(StringUtils.isBlank(key)){
return false;
}
//delete all white space
key= StringUtils.deleteWhitespace(key);
//Split String using the - separator
String[] keySplit = StringUtils.split(key, "-");
//check lengths of whole and parts
if(keySplit.length != 2
|| keySplit[0].length() != 4
|| keySplit[1].length() != 4) {
return false;
}
//Check if first part is numeric
if(!StringUtils.isNumeric(keySplit[0])){
return false;
}
//Check if second part contains only
//the four characters 'J', 'A', 'V' and 'A'
if(! StringUtils.containsOnly(keySplit[1]
,new char[]{'J', 'A', 'V', 'A'})){
return false;
}
//Check if the fourth character
//in the first part is a '0'
if(StringUtils.indexOf(keySplit[0], '0') != 3){
return false;
}
//If all conditions are fulfilled, key is valid.
return true;
}
In Listing 1, we utilize various methods provided in the org.apache.commons.lang.StringUtils class to validate a string according to all the rules that we defined earlier. The isBlank()method checks if the string is empty or null. The deleteWhitespace() method
ensures that the string is free of white spaces. We then split the string using
the split() method and validate the two portions using the isNumeric(), containsOnly(), and indexOf() methods.
Note that even though the indexOf() method is already present in J2SE, using the indexOf() in StringUtils is a better choice. Unlike the J2SE indexOf() method, with the StringUtils indexOf() you do not have to worry about null. Triggering NullPointerException is believed to be the most common error committed by Java programmers. Lang will ensure that you do not commit the same mistake. Even if you pass a null to the indexOf() method or any other method for that matter, it will not throw a NullPointerException. In the case of indexOf(), it will simply return -1.
So in just a few lines of pretty straightforward code, we have been able to achieve what would otherwise have taken many more lines of code and a lot more trouble. If we execute the checkLicenseKey() method using a main method as shown in Listing 2, you will get an output as shown in Listing 3.
Listing 2. The main() method
public static void main(String[] args) {
String []key= {"1210-JVAJ","1211-JVAJ", "210-JVAJ", "1210-ZVAJ"};
for (int i=0; i > Is Valid");
}
else{
System.out.println(key[i]+ " >> Is InValid");
}
}
}
Listing 3. The output
1210-JVAJ >> Is Valid
1211-JVAJ >> Is InValid
210-JVAJ >> Is InValid
1210-ZVAJ >> Is InValid
While org.apache.commons.lang.StringUtils has most of the methods meant for string manipulation, there are other classes that can also help. CharUtils and CharSetUtils provide utility methods for working with characters and character sets respectively. WordUtils is a class first seen in version 2.0 and is meant to house utility methods specifically for working with words. However, as there is significant overlap between what you can do with strings and words, this class does seem a little unnecessary. RandomStringUtils is a class that can help generate random strings based on various rules.
We will now look at another useful facet of Lang: the ability to work with dates and times.
|