سؤال

Essentially I need write a string method that receives two string arguments and replaces every character that exists in the second String with "" in the first. For example the first String toBeFixed = "I have a wonderful AMD CPU. I also like cheese." and the second String toReplaceWith ="oils". The string returned would be "I have a wnderfu AMD CPU. I a ke cheee."

Here is what I've got:

    public class removeChars
{
    public static String removeChars(String str, String remove) 
        {
            String fixed = str.replaceAll(remove,""); 

            return(fixed);
        }

}

I'm not sure if this is a misunderstanding of how the replaceAll method is used as I've seen things like

str = str.replaceAll("[aeiou]", "");

Ideally I'd figure out a way to toss my second string(remove) in there and then be done with it, but I'm not sure this is possible. I get a feeling this is a slightly more complicated problem... I'm not familiar with Array Lists and it seems the immutability of Strings might cause some issues for me.

This method should be able to deal with strings of any value entered. Any help or direction would be very much appreciated!

هل كانت مفيدة؟

المحلول

String.replaceAll takes a Regex statement as its first argument. Matching "oils" will this match specifically the phrase "oils".

Instead, you had the right idea in your post. Matching "["+remove+"]" will do the trick, so long as your removal string contains no reserved regex symbols such as brackets, periods, etc. (I'm not sure about duplicate characters.)

If it does, then first filter the removal string.

نصائح أخرى

Maybe not the most efficient solution but it's simple:

public class removeChars {
    public static String removeChars(String str, String remove) {
        String fixed = str;

        for(int i = 0; i < remove.length(); i++) 
             fixed = fixed.replaceAll(remove.charAt(i)+"","");  

        return fixed;
    }
}

This should work. replace works just like replaceAll - only with values rather than a regex

public class removeChars {
    public static String removeChars(String str, String remove) {
        String fixed = str; 

        for(int index = 0; index < remove.length; index++) {
            fixed = fixed.replace(remove.substring(index, index+1), "");
            // this replaces all appearances of every single letter of remove in str
        }

        return(fixed);
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top