替换字符串中的数组中的单词(Replacing words from array in a string)

编程入门 行业动态 更新时间:2024-10-25 22:24:57
替换字符串中的数组中的单词(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);

为什么它只取代最后一个字而不是全部替换它们?

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, if

and 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); }

更多推荐

本文发布于:2023-08-05 17:41:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1437378.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   单词   组中   Replacing   array

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!