从数组中替换文本正文中的单词

时间:2014-11-24 19:08:04

标签: c#

所以我试图让我的代码从一个名为txtBody的文本框中读取所有文本,并根据listA检查它们,如果listA中的任何单词出现,我想用适当的替换这些单词listB中的一个。我怎么能这样做?

对于参考列表A和B来自CSV,ListA是第一列,列表B是第2列,因此listA [1]是listB [1]的计数器部分。

这是我对列表的代码

  string body = txtBody.Text;
        var reader = new StreamReader(File.OpenRead("textwords.csv"));
        List<string> listA = new List<string>();
        List<string> listB = new List<string>();
        while (!reader.EndOfStream)
        {
            var line = reader.ReadLine();
            var values = line.Split(',');

            listA.Add(values[0]);
            listB.Add(values[1]);
        }

感谢您的帮助

3 个答案:

答案 0 :(得分:3)

以最简单的形式,您可以:

for(int i = 0; i < listA.Count; i++)
    body = body.Replace(listA[i], listB[i]);

但是,如果您在is中有listA之类的字词,那么this之类的内容将被部分替换。

<强>更新

如果您希望每个单词都被空格包围,您可以添加:

for (int i = 0; i < listA.Count; i++)
{
    var word1 = string.Format(@"(\b){0}(\b)", listA[i]);
    var word2 = string.Format(@"$1{0}$2", listB[i]);

    body = Regex.Replace(body, word1, word2, RegexOptions.IgnoreCase);
}

正则表达式将匹配单词,两边都有空格,并用新单词替换它,保持间距相同。

答案 1 :(得分:1)

我建议使用正则表达式。

for(int i = 0; i < listA.Count; i++)
{
    Regex myRege = new Regex(listA[i]);

    body = Regex.Replace(body,listB[i];
}

如果需要整个单词匹配:

for(int i = 0; i < listA.Count; i++)
{
    Regex myRege = new Regex(" " + listA[i] + " ");

    body = Regex.Replace(body,listB[i];
}

答案 2 :(得分:0)

使用Linq你可以这样:

string[] bodyWords = body.Split(' ');

// For each word contained inside body (s in bodyWords), if there is a match 
// in listA (i != 0), then get counterpart from listB (listB[i]), otherwise 
// leave it as it is. Use Join to reconstruct result string.
string result = string.Join(" ", (from s in bodyWords
                                  let i = listA.FindIndex(x => x == s)
                                  select i == -1 ? s : listB[i]).ToArray()); 

用这个输入:

string body = "John Smith";

List<string> listA = new List<string>() { "John", "Two", "Smith", "Four", "Five" };
List<string> listB = new List<string>() { "Martin", "TwoB", "Jones", "FourB", "FiveB"};;

上面的代码产生了结果:"Martin Jones"

性能方面,这可能不是最好的解决方案,但在linq中做事总是很有趣! :=)