如果我有一个字符串:
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);为什么它只取代最后一个字而不是全部替换它们?
If I've got 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.and I want to replace these words with "":
wood, chuck, ifand this is my code:
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);why it only replaces the last word instead of replacing them all?
最满意答案
因为你总是在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); }because you are iterating always on the original copy of Input and in last iteration only the last replace will take effect and hence you got the output result
foreach (string word in words) { input = input.Replace(word, string.Empty); } output = input;Hint
try for example to put a breakpoint on output = input.Replace(word, string.Empty); by pressing F9 and u will see what's the output
or
just place Console.Write(output); in the foreach loop
foreach (string word in words) { output = input.Replace(word, string.Empty); Console.Write(output); }更多推荐
发布评论