用另一个字符串中的每个字符替换字符串中的字符
问题描述:
本质上,我需要编写一个字符串方法,它接收两个字符串参数,并用第一个字符串中的“”替换第二个字符串中存在的每个字符。例如第一个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)
扔在那里,然后用它做,但我不确定这是可能的。我感觉这是一个稍微复杂的问题......我对Array列表不熟悉,似乎Strings的不变性可能会给我带来一些问题。
该方法应该能够处理输入的任何值的字符串。任何帮助或方向将非常感激!
答
String.replaceAll
将正则表达式作为第一个参数。匹配"oils"
这将特别匹配短语“油”。
相反,你在你的文章中有正确的想法。匹配"["+remove+"]"
将做的伎俩,只要您的删除字符串不包含保留的正则表达式符号,如括号,句点等(我不知道重复的字符。)
如果是这样,那么首先筛选删除串。
答
这应该工作。 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);
}
}
答
也许不是最有效的解决方案,但它很简单:
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;
}
}
工程,我需要的。谢谢!我不确定我明白为什么这个语法工作。连接的目的是什么? – supertommy 2013-04-25 07:28:41
正如我所说的,'replaceAll'采用[正则表达式](http://www.regular-expressions.info/java.html)(正则表达式)语句作为输入。正则表达式语法是这样的:括号表示一组可能的字符 - 任何其他未修改的字符集都是一个字面集。该链接值得一读。正则表达式功能强大且有用。 – Zyerah 2013-04-25 07:31:11