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?
Advertisement
Answer
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).