3

I have this string :

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

I just want the numbers to be stored in the array result[] like

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

Can anyone help me with this.

3
  • so you want to skip second position in the array? And how you determine which one to skip? Commented Oct 12, 2011 at 16:32
  • actually I got that string from textbox, so clarity I just represented as a string Commented Oct 12, 2011 at 16:37
  • So make it a string, just because its an example, doesn't give you a reason to be lazy. Commented Oct 12, 2011 at 17:22

4 Answers 4

7
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"
Sign up to request clarification or add additional context in comments.

Comments

2

How about this?

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

Comments

2
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);

Comments

1
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);                    
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.