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
I'll answer your questions:
1 - why do we need to do setLength()? without which I am getting java.lang.StringIndexOutOfBoundsException: String index out of range: 0
Initially your string buffer has no characters. You need to call setLength
in order to populate your empty string buffer with characters. Null characters, '\0', (or junk characters as you call them) are added to the string buffer so that it reaches the specified length. If you don't, you get a StringIndexOutOfBoundsException
because there are no characters in your string buffer. See Javadocs on StringBuffer#setLength.
So at the end of your method your string buffer has: [t][t][r][\0][\0][\0]
2 - '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?
You can remove the null characters by calling: r.toString().trim()
or r.substring(0,current)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With