0

本质上,我需要编写一个字符串方法,它接收两个字符串参数,并将第二个字符串中存在的每个字符替换为第一个字符串中的“”。例如第一个String toBeFixed = "I have a wonderful AMD CPU. I also like cheese."和第二个String toReplaceWith ="oils"The string returned would be "I have a wnderfu AMD CPU. I a ke cheee."

这是我所拥有的:

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

            return(fixed);
        }

}

我不确定这是否是对如何使用 replaceAll 方法的误解,因为我已经看到了类似的东西

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

理想情况下,我会想办法把我的第二根绳子扔进去(remove),然后完成,但我不确定这是否可能。我觉得这是一个稍微复杂的问题......我不熟悉数组列表,似乎字符串的不变性可能会给我带来一些问题。

此方法应该能够处理输入的任何值的字符串。任何帮助或指导将不胜感激!

4

3 回答 3

1

String.replaceAll将 Regex 语句作为其第一个参数。匹配"oils"将专门匹配短语“油”。

相反,您在帖子中的想法是正确的。"["+remove+"]"只要您的删除字符串不包含保留的正则表达式符号,例如括号、句点等,匹配就可以解决问题。(我不确定重复字符。)

如果是,则首先过滤删除字符串。

于 2013-04-25T07:11:53.407 回答
1

也许不是最有效的解决方案,但它很简单:

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;
    }
}
于 2013-04-25T07:18:50.207 回答
0

这应该有效。replace就像replaceAll- 只使用值而不是正则表达式

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);
    }
}
于 2013-04-25T07:17:55.503 回答