【问题标题】:replacing multiple words in a string with multiple words用多个单词替换字符串中的多个单词
【发布时间】:2020-09-11 07:20:42
【问题描述】:

所以我想要做的是我有一个列表

List<string> words = new List<string>();
            words.AddRange(new string[]{ "list of words", "i want to replace" })

现在我想从文本框中获取文本并从列表“单词”中搜索单词,并将它们全部替换为相同的文本 + 某些东西,对不起,如果这令人困惑或解释不清,但我做了我的最好的,感谢所有的帮助! :D

【问题讨论】:

  • 您能否向我们展示一些您正在努力实现的目标 - 之前和之后的示例。
  • 您似乎需要一个不同的结构来保存您的替换映射。在我看来,您的“单词列表”是一个 single 字符串。我猜你真正想要的是单词和替换的配对。 Dictionay&lt;string, string&gt; 在这里会是一个更好的选择
  • 如果你展示你的字符串之前的样子和你希望它之后的样子,这将很有用。
  • 您只想替换整个单词吗?或者如果这个词是另一个词的一部分?比如用"TextBox"中的"TextSuffix"替换"Text",这将导致"TextSuffixBox"

标签: c#


【解决方案1】:

如果我的理解正确,您希望实现以下目标:

string textboxString = "Text from Textbox";
List<string> words = new List<string>();
words.Add("Text");

foreach(string word in words)
{
    textboxString = textboxString.Replace(word, word + " + something");
}

你也可以使用Regex.Replace();

【讨论】:

  • string.Replace() 返回一个新字符串,因为String 是不可变的。你的代码最终什么也没做。
  • 抱歉,现在改了
【解决方案2】:

按照我理解您的问题的方式,您想在某些词中添加一些内容。如果您希望根据单词更改某些内容,则需要字典(嗯...需要是一个强词)

    string textboxString = "Text from Textbox";
    Dictionary<string, string> words = new Dictionary<string, string>();
    words.Add("Text", "Something");
    words.Add("from", "SomethingElse");
    
    foreach (var key in words)
        textboxString = textboxString.Replace(key.Key, key.Key + key.Value);

这应该给你:

"TextSomething fromSomethingElse TextSomethingbox"

【讨论】:

  • "TextSomethingbox" 这个替换可能不是有意的,需要作者进行一些澄清。但你做了一个很好的案例!
  • 这可能是对的:-) 最初我已经翻转了搜索,但我重新阅读了这个问题。我最初的答案是: foreach(string s in textboxString.split(''')) 等,所以它循环遍历文本框中的单词并将它们匹配到 dic 中。
猜你喜欢
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-05
  • 1970-01-01
  • 2019-01-29
  • 1970-01-01
  • 2023-02-07
相关资源
最近更新 更多