KansaiRobot
KansaiRobot

Reputation: 9912

Efficient way to process substrings from a string

I have the following string (actually with more elements)

string content= "  {
                  element1: one
                  element2: two
                  element3:three
                   }
                   {
                   element1: uno
                   element2: dos
                   element3:tres
                   }"; 

and I need to process this string element by element (an element is what is inside a { and a } , in the above case two elements but it can contain more)

Now, I am thinking of doing the usual IndexOf to find { and } and then extracting the substring one by one.

My question is: is there a more efficient way of doing this?

Upvotes: 0

Views: 85

Answers (1)

John Wu
John Wu

Reputation: 52230

Assuming your format doesn't have any more quirks to it (e.g. delimiters or escape sequences) you can parse that string with a bit of LINQ.

    var data = content.Replace("}","").Replace("\r\n","\n").Split('{')
        .Select
        ( 
            block => block.Split('\n')
            .Where
            ( 
                line => !string.IsNullOrWhiteSpace(line)
            )
            .Select
            ( 
                line => line.Split(new char[] {':'}, 2)
            )
            .ToDictionary
            ( 
                fields => fields[0].Trim(), 
                fields => fields[1].Trim()
            )
        )
        .ToList();

    foreach (var list in data)
    {
        foreach (var entry in list)
        {
            Console.WriteLine("{0}={1}", entry.Key, entry.Value);
        }
    }

Output:

element1=one
element2=two
element3=three
element1=uno
element2=dos
element3=tre

DotNetFiddle

Upvotes: 1

Related Questions