Unknowin
Unknowin

Reputation: 11

IndexOf in for loop only removes one character

I want to use IndexOf inside a for loop so I can remove all instances of a word/character in a phrase, but my code only deletes the first instance even if I think it should remove the others. Here is my code:

    String phrase = "yes no YES NO";
    String del = "no";
    for (int i=0;i<phrase.length();i++) {
        if (phrase.indexOf(del) == i) {
            System.out.print("");
        }
        else 
            System.out.print(phrase.charAt(i));
    }

The code above gives me this result:

yes o YES NO

I want my code to give me

yes YES

but I don't understand why indexOf only removes one character and I don't understand how I can use .equalsIgnoreCase with my string to also remove "NO". How should I change my code to get this answer?

Upvotes: 0

Views: 52

Answers (2)

Eldar B.
Eldar B.

Reputation: 1347

indexOf is used in order to find a specific character in a String. If you'd like to remove a specific value within a String, I suggest using the replaceAll method.

Also, note that both indexOf and replaceAll are case-sensitive. That means that "no" and "NO" are different, since "NO" is upper-cased (that's also the reason the "NO" is left untouched).

Use target.replaceAll("(?i)" + Pattern.quote("text"), ""); for a case-insensitive variant (as explained in this post).

Upvotes: 2

MehranB
MehranB

Reputation: 1525

Try this:

String newPhrase = phrase.replaceAll(del," ");

and then print newPhrase.

Also, "no" and "NO" are two different values. one is uppercase and the other is lower case. so if you don't want your code to be case sensitive, you need to check for the lowercase of "del" in the lowercase of "phrase".

Upvotes: 0

Related Questions