Разбор строки в массив в C # - PullRequest
3 голосов
/ 12 октября 2011

У меня есть эта строка:

string resultString="section[]=100&section[]=200&section[]=300&section[]=400";

Я просто хочу, чтобы числа сохранялись в массиве result[] как

result[0]=100
result[1]=200
result[3]=300
result[4]=400

Может кто-нибудь помочь мне с этим.

Ответы [ 4 ]

7 голосов
/ 12 октября 2011
NameValueCollection values = HttpUtility.ParseQueryString("section[]=100&section[]=200&section[]=300&section[]=400");
string[] result = values["section[]"].Split(',');
// at this stage 
// result[0] = "100"
// result[1] = "200"
// result[2] = "300"
// result[3] = "400"
2 голосов
/ 12 октября 2011

Как насчет этого?

        string s ="section[]=100&section[]=200&section[]=300&section[]=400";
        Regex r = new Regex(@"section\[\]=([0-9]+)(&|$)");

        List<int> v = new List<int>();

        Match m=r.Match(s);
        while (m.Success){
            v.Add(Int32.Parse(m.Groups[1].ToString()));
            m=m.NextMatch();
        }

        int[]result = v.ToArray();
2 голосов
/ 12 октября 2011
str.Split('&')
   .Select(s=>s.Split('=')
               .Skip(1)
               .FirstOrDefault()).ToArray();

OR

 str.Split(new[] { "section[]=" }, StringSplitOptions.RemoveEmptyEntries)
    .Select(s => s.Replace("&", ""))
    .Select(Int32.Parse).ToArray();

OR

        var items = new List<string>();
        foreach (Match item in Regex.Matches(str, @"section\[\]=(\d+)"))
            items.Add(item.Groups[1].Value);
1 голос
/ 12 октября 2011
string x = "section[]=100&section[]=200&section[]=300&section[]=400";

// Split into a list
string[] vals = x.Split('&');
List<int> results = new List<int>();
foreach (string aResult in vals)
{
    int result = 0;
    string[] val = aResult.Split('=');

    // Get right hand side
    if (val.Length == 2 && int.TryParse(val[1], out result))
        results.Add(result);                    
}
...