Reputation: 21
I am trying to remove the word "Bye" every time it appears in the String. It works for the first time "Bye" appears, but then begins deleting the wrong characters.
String str = "HiByeHiByeByByeHiHiHi";
StringBuilder sb = new StringBuilder(str);
for(int i=0; i<str.length()-2; i++){
if(str.substring(i,i+3).equals("Bye")){
sb.delete(i,i+3);
}
}
System.out.println(sb.toString());
}
Upvotes: 1
Views: 1085
Reputation: 48297
no need to use a StrinBuilder, String#replace
can do that, just use the method replace
String str = "HiByeHiByeByByeHiHiHi";
str = str.replace("Bye", "");
System.out.println(str);
Upvotes: 4
Reputation: 19335
Some problems in the code
i must be decremented in case of delete or if
changed by while
String str = "HiByeHiByeByByeHiHiHi";
StringBuilder sb = new StringBuilder( str );
for ( int i = 0 ; i < sb.length() - 2 ; i++ ) {
while ( sb.substring( i, i + 3 ).equals( "Bye" ) ) {
sb.delete( i, i + 3 );
}
}
System.out.println( sb.toString() );
Upvotes: 0
Reputation: 1234
You can use replaceAll.
String str = "HiByeHiByeByByeHiHiHi";
System.out.println(str.replaceAll("Bye", ""));
It will print:
HiHiByHiHiHi
Upvotes: 1
Reputation: 60046
Why you don't use String::replace
method, you can replace all the occurrence in one shot :
str.replace("Bye", "")
so you need just this :
String str = "HiByeHiByeByByeHiHiHi";
System.out.println(str.replace("Bye", ""));
Outputs
HiHiByHiHiHi
Upvotes: 0