【问题标题】:Split out ints from string从字符串中拆分出整数
【发布时间】:2010-09-08 23:21:09
【问题描述】:

假设我有一个网页当前通过 url 参数接受单个 ID 值:
http://example.com/mypage.aspx?ID=1234

我想将其更改为接受 ID 的 列表,如下所示:
http://example.com/mypage.aspx?IDs=1234,4321,6789

因此,我的代码可以通过 context.Request.QueryString["IDs"] 将其作为字符串提供给我。将该字符串值转换为 List 的最佳方法是什么?

编辑:我知道如何在逗号上使用 .split() 来获取字符串列表,但我问是因为我不知道如何轻松将该字符串列表转换为 int列表。这仍然在 .Net 2.0 中,所以没有 lambdas。

【问题讨论】:

    标签: .net string .net-2.0


    【解决方案1】:

    从 URL 中提取值后,您可以使用 string.Split() 来拆分它们。

    string[] splitIds = ids.split(',');
    

    【讨论】:

      【解决方案2】:

      我能想到的就是循环遍历字符串列表(您从执行拆分中获得)并一个接一个地对它们执行类似int.TryParse() 的操作,然后将它们放入一个新的List<int> 中。将它封装在一个不错的小助手方法中,它不会太可怕。

      【讨论】:

        【解决方案3】:

        您只需要遍历它们并 int.TryParse 中的每一个。之后只需添加到列表中。

        没关系 - @Splash 打败了我

        【讨论】:

          【解决方案4】:

          您可以从数组中实例化 List

          VB.NET:

          Dim lstIDs as new List(of Integer)(ids.split(','))
          

          如果数组包含非 int 元素,这很容易出现转换错误

          【讨论】:

          • 这个问题是,只有一个铸造错误会杀死整个列表,但我仍然投票赞成,也许这就是我应该采取的行为。
          【解决方案5】:

          split 是首先想到的,但它返回的是一个数组,而不是一个列表; 您可以尝试以下方法:

          
          List<int> intList = new List<int>;
          
          foreach (string tempString in ids.split(',')
          {
              intList.add (convert.int32(tempString));
          }
          
          

          【讨论】:

            【解决方案6】:

            这样的事情可能会奏效:

            public static IList<int> GetIdListFromString(string idList)
            {
                string[] values = idList.Split(',');
            
                List<int> ids = new List<int>(values.Length);
            
                foreach (string s in values)
                {
                    int i;
            
                    if (int.TryParse(s, out i))
                    {
                        ids.Add(i);
                    }
                }
            
                return ids;
            }
            

            然后使用:

            string intString = "1234,4321,6789";
            
            IList<int> list = GetIdListFromString(intString);
            
            foreach (int i in list)
            {
                Console.WriteLine(i);
            }
            

            【讨论】:

            • 很好,我正要发布完全相同的答案:(
            【解决方案7】:
            List<int> convertIDs = new List<int>;
            string[] splitIds = ids.split(',');
            foreach(string s in splitIds)
            {
                convertIDs.Add(int.Parse(s));
            }
            

            为了完整起见,您需要在 for 循环(或 int.Parse() 调用周围)放置 try/catch,并根据您的要求处理错误。您也可以像这样执行 tryparse():

            List<int> convertIDs = new List<int>;
            string[] splitIds = ids.split(',');
            foreach(string s in splitIds)
            {
                int i;
                int.TryParse(out i);
                if (i != 0)
                   convertIDs.Add(i);
            }
            

            【讨论】:

              【解决方案8】:

              要继续上一个答案,只需遍历 Split 返回的数组并转换为新的整数数组即可。下面的 C# 示例:

                      string[] splitIds = stringIds.Split(',');
              
                      int[] ids = new int[splitIds.Length];
                      for (int i = 0; i < ids.Length; i++) {
                          ids[i] = Int32.Parse(splitIds[i]);
                      }
              

              【讨论】:

                【解决方案9】:

                如果你喜欢函数式风格,你可以试试类似

                    string ids = "1,2,3,4,5";
                
                    List<int> l = new List<int>(Array.ConvertAll(
                        ids.Split(','), new Converter<string, int>(int.Parse)));
                

                没有 lambda,但您确实有转换器和谓词以及其他可以由方法制成的好东西。

                【讨论】:

                  【解决方案10】:

                  我认为最简单的方法是如前所示进行拆分,然后循环遍历这些值并尝试转换为 int。

                  class Program
                  {
                      static void Main(string[] args)
                      {
                          string queryString = "1234,4321,6789";
                  
                          int[] ids = ConvertCommaSeparatedStringToIntArray(queryString);
                      }
                  
                      private static int[] ConvertCommaSeparatedStringToIntArray(string csString)
                      {
                          //splitting string to substrings
                          string[] idStrings = csString.Split(',');
                  
                          //initializing int-array of same length
                          int[] ids = new int[idStrings.Length];
                  
                          //looping all substrings
                          for (int i = 0; i < idStrings.Length; i++)
                          {
                              string idString = idStrings[i];
                  
                              //trying to convert one substring to int
                              int id;
                              if (!int.TryParse(idString, out id))
                                  throw new FormatException(String.Format("Query string contained malformed id '{0}'", idString));
                  
                              //writing value back to the int-array
                              ids[i] = id;
                          }
                  
                          return ids;
                      }
                  }
                  

                  【讨论】:

                    【解决方案11】:

                    没有冒犯那些提供明确答案的人,但许多人似乎是在回答您的问题,而不是解决您的问题。您需要多个 ID,因此您认为可以这样:

                    http://example.com/mypage.aspx?IDs=1234,4321,6789

                    问题在于这是一个不可靠的解决方案。以后如果你想要多个值,如果它们有逗号怎么办?更好的解决方案(这在查询字符串中完全有效)是使用多个具有相同名称的参数:

                    http://example.com/mypage.aspx?ID=1234;ID=4321;ID=6789

                    然后,您使用的任何查询字符串解析器都应该能够返回 ID 列表。如果它不能处理这个(并且也处理分号而不是&符号),那么它就坏了。

                    【讨论】:

                    • asp.net 对 page.aspx?id=1,2,3,4&otherid=4,5,6,7 没有任何问题,所以我不明白为什么逗号分隔的列表不是强大的解决方案。
                    • 因为如前所述,如果允许 包含逗号,则在逗号上拆分是有问题的。 CGI 协议允许同名的多个参数,因此整个“我能不能用逗号分割”的问题变得没有实际意义。这就是重复参数名称的用途。
                    • 我认为如果列出了字母数字 ID 或 GUID,则 ID 内不会出现逗号,从这个角度来看,逗号是一种可靠的解决方案吗?但我想可能还有其他问题,例如认为链接在逗号结束时结束的 Wiki 语法解析器?
                    • 这是一个可怕的想法!如果将来值包含“;”怎么办? “;”不比“,”好——如果你想准时,rfc 都不允许这样做
                    • @Nas:抱歉,但这是不正确的。不打算用作分隔符的字符串中的分号 (;) 需要进行 uri 转义(在本例中为 %3B),因为它是保留字符。请参阅 RFC 2396 - ietf.org/rfc/rfc2396.txt 的第 2.2 节。根据定义,任何不处理此问题的查询字符串解析器都会被破坏。你说得对,',' 也是一个保留字符,必须转义,但你无法判断它是转义到分隔还是转义,因为它是一个有效值。
                    【解决方案12】:

                    最终代码 sn-p 从所有建议中得到我希望是最好的:

                    Function GetIDs(ByVal IDList As String) As List(Of Integer)
                        Dim SplitIDs() As String = IDList.Split(new Char() {","c}, StringSplitOptions.RemoveEmptyEntries)
                        GetIDs = new List(Of Integer)(SplitIDs.Length)
                        Dim CurID As Integer
                        For Each id As String In SplitIDs
                            If Integer.TryParse(id, CurID) Then GetIDs.Add(CurID)
                        Next id
                    End Function
                    

                    我希望能够在一两行内联代码中完成。一行来创建字符串数组,并希望在框架中找到一些我还不知道的东西来处理将它导入到可以智能地处理强制转换的 List 。但是,如果我必须将其移至方法,那么我会的。是的,我正在使用 VB。我只是更喜欢 C# 来提问,因为它们会吸引更多的听众,而且我的流利程度也差不多。

                    【讨论】:

                      【解决方案13】:

                      我看到my answer 来得比较晚,即其他几个人也写了同样的内容。因此,我提出了一种使用正则表达式来验证和划分字符串的替代方法。

                      class Program
                      {
                          //Accepts one or more groups of one or more digits, separated by commas.
                          private static readonly Regex CSStringPattern = new Regex(@"^(\d+,?)*\d+$");
                      
                          //A single ID inside the string. Must only be used after validation
                          private static readonly Regex SingleIdPattern = new Regex(@"\d+");
                      
                          static void Main(string[] args)
                          {
                              string queryString = "1234,4321,6789";
                      
                              int[] ids = ConvertCommaSeparatedStringToIntArray(queryString);
                          }
                      
                          private static int[] ConvertCommaSeparatedStringToIntArray(string csString)
                          {
                              if (!CSStringPattern.IsMatch(csString))
                                  throw new FormatException(string.Format("Invalid comma separated string '{0}'",
                                                                          csString));
                      
                              List<int> ids = new List<int>();
                              foreach (Match match in SingleIdPattern.Matches(csString))
                              {
                                  ids.Add(int.Parse(match.Value)); //No need to TryParse since string has been validated
                              }
                              return ids.ToArray();
                          }
                      }
                      

                      【讨论】:

                        猜你喜欢
                        • 1970-01-01
                        • 2020-12-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 2016-12-06
                        • 1970-01-01
                        相关资源
                        最近更新 更多