开发者

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

开发者 https://www.devze.com 2022-12-27 22:28 出处:网络
how to get from such string \' name1{value1开发者_JAVA百科,value2};name2{value3}; ... nameN{value12, valueN} \'

how to get from such string ' name1{value1开发者_JAVA百科,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)?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消