Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove a character from a String?

Tags:

java

string

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:

  1. why do we need to do setLength()? without which I am getting java.lang.StringIndexOutOfBoundsException: String index out of range: 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?

like image 261
jai Avatar asked Oct 16 '25 18:10

jai


2 Answers

Why not just use replaceAll? java.lang.String.replaceAll

like image 117
Asgeir Avatar answered Oct 19 '25 10:10

Asgeir


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)

like image 42
dogbane Avatar answered Oct 19 '25 08:10

dogbane