public static String removeChar(String s, char c) {
StringBuffer r = new StringBuffer( s.length() );
r.setLength( s.length() );
int current = 0;
for (int i = 0; i < s.length(); i ++) {
char cur = s.charAt(i);
if (cur != c) r.setCharAt( current++, cur );
}
return r.toString();
}
I’ve found the above code here.
Two Questions:
-
why do we need to do setLength()? without which I am getting java.lang.StringIndexOutOfBoundsException: String index out of range: 0
-
‘ttr’ and three junk chars are coming when I run this program with parameters – “teeter” and “e”. How to remove the unused whitespaces in the buffer?
Why not just use replaceAll? java.lang.String.replaceAll