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:
thanks a lot,
it was great help.
Rofl: if(null ==null)return null;
Try trimming the character ":" from the input string "a6" ... it'll fail
Thank you guys, fixed code uploaded.
Post a Comment