Trying to remove all of the characters that are in String S2 from S1. Example would be: S1 = Mississippi River, S2 = is. Return would be S1 and it would be Mpp Rver.
public static String removeLetters(String S1, String S2){
for(int i=0;i<S1.length();i++){
for(int j=0;j<S2.length();j++){
if(S2.charAt(i) == S1.charAt(j))
S1.charAt(j) = ""; //this does not work but essentially what i want.
}
}
}
I have tried
String S1 = S1.removeAll
and
S1 = S1.remove
The problem is that remove all takes a String String param and .remove takes a char char, neither of which works. I've fought this for a day, can't get it, any help for noobz? :) thank you all greatly as always.
One simple approach would be something like:
public static String removeLetters(String source, String lettersToRemove) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < source.length(); i++) {
if (lettersToRemove.indexOf(source.charAt(i)) == -1) {
builder.append(source.charAt(i));
}
}
return builder.toString();
}
Or:
public static String removeLetters(String source, String lettersToRemove) {
for (int i = 0; i < lettersToRemove.length(); i++) {
source = source.replace(lettersToRemove.substring(i, i + 1), "");
}
return source;
}
While the approaches using regular expressions will work in many cases, you'd need a bit more work to make them robust against things like "-" within lettersToRemove
. It really depends on your requirements. (As noted in Sabuj's answer, Pattern.quote
may well be enough here... but I'd want to validate that for myself with a few weird cases.)
See more on this question at Stackoverflow