Search code examples
c#.netstringarraysarraycollection

Converting a string into ArrayCollection (C#, see string below)


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)?


Solution

  • 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().