Friday, February 27, 2009

Trim prefix and suffix any characters

java.lang.String has API for trim, which will remove whitespaces(blankspace) from prefix and sufix of the string.

How to do the same for other characters which are not required and has to be truncated. We can even write a regular expression(regexps) to format this.

For example,
aaaaWelcomeaaaa
in this 'a' needs to be removed/trim and output String has to be like below
Welcome

Find the API implementation below which helps us to achieve this

System.out.println(trim("aaaaWelcomeaaaa",'a'));

/** Trim characters in prefix and suffix
* @param str String 
* @param ch character which has to be removed
* @return null, if str is null, otherwise string will be returned 
* without character prefixed/suffixed
*/
public static String trim(String str,char ch) {
if(null ==str)return null;
str=srt.trim();
int count=str.length();
int len = str.length();
int st = 0;

char[] val = str.toCharArray();   

while ((st < len) && (val[st] == ch)) {
st++;
}
while ((st < len) && (val[len - 1] == ch)) {
len--;
}
return ((st > 0) || (len < count)) ? str.substring(st, len) : str;
}

4 comments:

krongob said...

thanks a lot,
it was great help.

Unknown said...

Rofl: if(null ==null)return null;

Anonymous said...

Try trimming the character ":" from the input string "a6" ... it'll fail

Krishna said...

Thank you guys, fixed code uploaded.

Post a Comment

Recent Posts

Unix Commands | List all My Posts

Texts

This blog intended to share the knowledge and contribute to JAVA Community such a way that by providing samples and pointing right documents/webpages. We try to give our knowledege level best and no guarantee can be claimed on truth. Copyright and Terms of Policy refer blogspot.com