views:

190

answers:

1

how to get from such string ' name1{value1,value2};name2{value3}; ... nameN{value12, valueN} '

Array or arrays in such form: Array = {string, int};{string, int};{string, int};

like this:

{
 { name1 ; value1}
 { name1 ; value2}
 { name2 ; value3}
...
 { nameN ; valueN}
}

in C# (.net)?

+1  A: 

If you can assume that the document will always be well-formed:

List<KeyValuePair<string, int>> results = new List<KeyValuePair<string, int>>();
foreach (string line in File.ReadAllLines("input.txt"))
{
    Match match = Regex.Match(line, @"^\s*{\s*(.*?)\s*;\s*(\d+)\s*}\s*$");
    if (match.Success)
    {
        string s = match.Groups[1].Value;
        int i = int.Parse(match.Groups[2].Value);
        results.Add(new KeyValuePair<string,int>(s,i));
    }
}

foreach (var kvp in results)
    Console.WriteLine("{0} ; {1}", kvp.Key, kvp.Value);

Result:

name1 ; 1
name1 ; 2
name2 ; 3
nameN ; 23

If name1, name2, ... , nameN are unique and you don't care about the order then you may prefer to use a Dictionary instead of a List. If you really want an array instead of a list (you probably don't) then you can use ToArray().

Mark Byers
Can I swich to use dictionary just bu replacing ' List<KeyValuePair<string, int>> results = new List<KeyValuePair<string, int>>(); ' to ' Dictionary<KeyValuePair<string, int>> results = new Dictionary<KeyValuePair<string, int>>(); ' ?
Blender
@Ole Jak: Use `Dictionary<string, int>` and you also need to change the Add line to `results.Add(s, i);`.
Mark Byers