简体   繁体   中英

C# How to implement CSV file into this code

Hi I am fairly new to coding, I have a piece of code that searches for a string and replaces it with another string like so:

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

If I want to use a CSV file that contains a lot of words and their replacements, for example, LOL,Laugh Out Loud, and ROFL, Roll Around Floor Laughing. How would I implement that?

Create a text file that looks like (you could use commas, but I like pipes ( | )):

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

Then create a tiny helper class:

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

And finally, call this code:

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

The result is:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM