Vinny Vinny - 7 months ago 12
Java Question

Character deletion from a string in java

I have a string

*dfgi*kjklx
. I want to delete the character before and after * the output should be

fgjklx


I have written my code like this but it shows me index out of bound error.

String t = "*dfgi*kjklx";
for(int i = 0; i < s.length(); i++)
{
String temp = s.charAt(i);
if(temp == ‘*’)
{
t = t.replace(s.charAt(i), '');
t = t.replace(s.charAt(i-1), '');
t = t.replace(s.charAt(i+1), '');
System.out.println("String: " + t);
}
}

Answer

I might approach this with a StringBuilder:

StringBuilder sb = new StringBuilder(t.length());
for (int i = 0; i < t.length(); ++i) {
  if (t.charAt(i) != '*'                     // Check the current character.
      && (i == 0 || t.charAt(i - 1) != '*')  // Check the prev character.
      && (i + 1 >= t.length() || t.charAt(i + 1) != '*')) {  // Check the next.
    sb.append(t.charAt(i));
  }
}
t = sb.toString();