[英]Replacing words from array in a string
如果我有一个字符串:
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);
上设置一个断点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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.