Shawn Shawn - 3 years ago 173
C# Question

C# string parse

I have string like this

string temp = "'ADDR_LINE_2','MODEL','TABLE',5,'S','Y','C40','MUL,NBLD,NITA,NUND','','Address line 2'"


Each pair of single quote is a field delimited by a comma. I want to empty the 8th field in the string. I cannot simply do
replace("MUL,NBLD,NITA,NUND","")
because that field could contain anything. also please note the the 4th field is a number and therefore has no single quote around
5
.

How can I achieve this?

Answer Source
static void Main()
{
    var temp = "'ADDR_LINE_2','MODEL','TABLE',5,'S','Y','C40','MUL,NBLD,NITA,NUND','','Address line 2'";

    var parts = Split(temp).ToArray();
    parts[7] = null;
    var ret = string.Join(",", parts);

    // or replace the above 3 lines with this...        
    //var ret = string.Join(",", Split(temp).Select((v,i)=>i!=7 ? v : null));

    //ret == "'ADDR_LINE_2','MODEL','TABLE',5,'S','Y','C40',,'','Address line 2'"
}

public static IEnumerable<string> Split(string input, char delimiter = ',', char quote = '\'')
{
    string temp = "";
    bool skipDelimiter = false;

    foreach (var c in input)
    {
        if (c == quote)
            skipDelimiter = !skipDelimiter;
        else if (c == delimiter && !skipDelimiter)
        {
            //do split
            yield return temp;
            temp = "";
            continue;
        }

        temp += c;
    }
    yield return temp;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download