【问题标题】:Parsing a string to an array in C#在 C# 中将字符串解析为数组
【发布时间】:2011-12-06 07:10:47
【问题描述】:

我有这个字符串:

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

我只想将数字存储在数组result[] 中,就像

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

谁能帮帮我。

【问题讨论】:

  • 所以你想跳过数组中的第二个位置?以及如何确定要跳过哪一个?
  • 实际上我是从文本框中得到那个字符串的,所以我只是把它表示为一个字符串
  • 所以让它成为一个字符串,仅仅因为它是一个例子,并不能给你一个懒惰的理由。

标签: c# regex c#-4.0 c#-3.0


【解决方案1】:
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】:

这个怎么样?

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

【讨论】:

    【解决方案3】:
    str.Split('&')
       .Select(s=>s.Split('=')
                   .Skip(1)
                   .FirstOrDefault()).ToArray();
    

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

            var items = new List<string>();
            foreach (Match item in Regex.Matches(str, @"section\[\]=(\d+)"))
                items.Add(item.Groups[1].Value);
    

    【讨论】:

      【解决方案4】:
      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);                    
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-23
        • 1970-01-01
        • 2017-02-02
        • 1970-01-01
        • 1970-01-01
        • 2013-03-30
        • 1970-01-01
        • 2010-10-03
        相关资源
        最近更新 更多