shanemcg
shanemcg

Reputation: 21

Java deleting all occurrences of word in String

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

Answers (4)

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

Nahuel Fouilleul
Nahuel Fouilleul

Reputation: 19335

Some problems in the code

  • str is still used, but it's an invariant, it should be sb instead
  • 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

melli-182
melli-182

Reputation: 1234

You can use replaceAll.

String str = "HiByeHiByeByByeHiHiHi";
System.out.println(str.replaceAll("Bye", "")); 

It will print:

HiHiByHiHiHi

Upvotes: 1

Youcef LAIDANI
Youcef LAIDANI

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

Related Questions