如果我有一个字符串:
How much wood would a woodchuck chuck
if a woodchuck could chuck wood?
Just as much as a woodchuck would
if a woodchuck could chuck wood.
我希望用""
替换这些字词:
wood, chuck, if
这是我的代码:
string[] words = new string[] { "wood", "chuck", "if" };
string input = woodchuckText;
string output = string.Empty;
foreach (string word in words)
{
output = input.Replace(word, string.Empty);
}
Console.Write(output);
为什么它只替换掉最后一个单词而不是全部替换它们?
答案 0 :(得分:4)
input
永远不会改变,所以基本上你得到的输出就像你只替换了你的最后一个单词一样。
要解决此问题,请改为:
output = input;
foreach (string word in words)
{
output = output.Replace(word, string.Empty);
}
答案 1 :(得分:3)
因为您总是在Input
的原始副本上进行迭代,并且在最后一次迭代中,只有最后一次替换才会生效,因此您获得了output
结果
foreach (string word in words)
{
input = input.Replace(word, string.Empty);
}
output = input;
<强>提示强>
尝试通过按output = input.Replace(word, string.Empty);
在F9
上设置断点,你会看到输出是什么
或强>
将Console.Write(output);
放在foreach循环中
foreach (string word in words)
{
output = input.Replace(word, string.Empty);
Console.Write(output);
}
答案 2 :(得分:3)
您还可以使用正则表达式:
string[] words = new string[] { "wood", "chuck", "if" };
var output = Regex.Replace(input, String.Join("|", words), "");
答案 3 :(得分:1)
因为每次迭代都要将output
设置为原始input
字符串。因此,只会在output
上设置最后一次迭代。调整逻辑以保持更新相同的字符串:
string[] words = new string[] { "wood", "chuck", "if" };
string input = woodchuckText;
string output = input;
foreach (string word in words)
{
output = output.Replace(word, string.Empty);
}
Console.Write(output);