Reputation: 9912
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
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
Upvotes: 1