在字符串中替换数组中的单词
本文关键字:单词 数组 替换 字符串 | 更新日期: 2023-09-27 18:12:24
如果我有一个字符串:
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);
为什么只替换最后一个单词而不是全部替换?
input
在替换后永远不会改变,所以基本上你得到的输出是一样的,如果你只替换了最后一个单词。
要解决这个问题,可以这样做:
output = input;
foreach (string word in words)
{
output = output.Replace(word, string.Empty);
}
因为您总是在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);
}
也可以使用正则表达式:
string[] words = new string[] { "wood", "chuck", "if" };
var output = Regex.Replace(input, String.Join("|", words), "");
因为每次迭代都将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);