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,
in this 'a' needs to be removed/trim and output String has to be like below

Find the API implementation below which helps us to achieve this


/** 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;
int count=str.length();
int len = str.length();
int st = 0;

char[] val = str.toCharArray();   

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

Recent Posts

Unix Commands | List all My Posts


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