C#如何在此代码中实现CSV文件

时间:2018-11-01 15:44:03

标签: c# arrays csv replace find

嗨,我是编码的新手,我有一段代码可以搜索一个字符串,并将其替换为另一个字符串,如下所示:

var replacements = new[]{
   new{Find="123",Replace="Word one"},
   new{Find="ABC",Replace="Word two"},
   new{Find="999",Replace="Word two"},
};

var myLongString = "123 is a long 999 string yeah";

foreach(var set in replacements)
{
   myLongString = myLongString.Replace(set.Find, set.Replace);
}

如果我想使用包含很多单词及其替换单词的CSV文件,例如,LOL,大声笑和ROFL,滚转地板笑声。我将如何实施?

1 个答案:

答案 0 :(得分:0)

创建一个看起来像(您可以使用逗号,但是我喜欢管道(|)的文本文件):

123|Word One
ABC|Word Two
999|Word Three
LOL|Laugh Out Loud
ROFL|Roll Around Floor Laughing

然后创建一个小助手类:

public class WordReplace
{
    public string Find { get; set; }
    public string Replace { get; set; }
}

最后,调用以下代码:

private static string  DoWordReplace()
{
    //first read in the data
    var fileData = File.ReadAllLines("WordReplace.txt");
    var wordReplacePairs = new List<WordReplace>();
    var lineNo = 1;
    foreach (var item in fileData)
    {
        var pair = item.Split(new[] {'|'}, StringSplitOptions.RemoveEmptyEntries);
        if (pair.Length != 2)
        {
            throw new ApplicationException($"Malformed file, line {lineNo}, data = [{item}] ");
        }
        wordReplacePairs.Add(new WordReplace{Find = pair[0], Replace = pair[1]});
        ++lineNo;
    }

    var longString = "LOL, 123 is a long 999 string yeah, ROFL";

    //now do the replacements
    var buffer = new StringBuilder(longString);
    foreach (var pair in wordReplacePairs)
    {
        buffer.Replace(pair.Find, pair.Replace);
    }

    return buffer.ToString();
}

结果是:

Laugh Out Loud, Word One is a long Word Three string yeah, Roll Around Floor Laughing