代码之家  ›  专栏  ›  技术社区  ›  Joel Coehoorn

从字符串中拆分整数

  •  10
  • Joel Coehoorn  · 技术社区  · 16 年前


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

    列表 ID的名称,如下所示:
    http://example.com/mypage.aspx?IDs=1234,4321,6789

    因此,我的代码可以通过 context.Request.QueryString[“IDs”]。 将该字符串值转换为列表的最佳方式是什么<int>?

    我知道如何对逗号执行.split()操作以获得字符串列表,但我之所以这样做是因为我不知道如何轻松地将该字符串列表转换为int列表。这仍然在.NET2.0中,因此没有lambdas。

    13 回复  |  直到 13 年前
        1
  •  13
  •   Ovid    16 年前

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

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

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

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

        2
  •  12
  •   Compile This    16 年前

    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);
    }
    
        3
  •  4
  •   user7658    16 年前

    您可以实例化一个列表<T>从一个数组中。

    VB.NET:

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

    如果数组包含非int元素,则很容易发生强制转换错误

        4
  •  2
  •   Mark Embling    16 年前

    我所能想到的就是在字符串列表上循环(这是通过执行拆分得到的)并执行以下操作 int.TryParse() 一个接一个地把它们放进一个新的 List<int> . 将它封装在一个好的小助手方法中,这样就不会太可怕了。

        5
  •  2
  •   Jesse Millikan    16 年前

    如果你喜欢功能性风格,你可以试试

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

    没有lambdas,但是您确实有转换器和谓词,以及其他可以从方法生成的好东西。

        6
  •  2
  •   Community Fabien Hure    7 年前

    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();
        }
    }
    
        7
  •  1
  •   Joel Coehoorn    16 年前

    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
    

    我希望能够在一行或两行内联代码中完成它。一行创建字符串数组,并希望在框架中找到一些我还不知道如何将其导入列表的内容<int>这样可以巧妙地处理演员阵容。但如果我必须把它转移到一种方法,那么我会的。是的,我在用VB。我只是更喜欢用C#提问,因为他们会吸引更多的观众,而我也一样流利。

        8
  •  1
  •   Richard C    16 年前

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

    
    List<int> intList = new List<int>;
    
    foreach (string tempString in ids.split(',')
    {
        intList.add (convert.int32(tempString));
    }
    
    
        9
  •  0
  •   Grokys    16 年前

    从URL提取值后,可以使用string.Split()拆分这些值。

    string[] splitIds = ids.split(',');
    
        10
  •  0
  •   sirrocco    16 年前

    你只需要通过它们,对每一个进行int.TryParse。之后,只需添加到列表中。

    别担心,@Splash打败了我

        11
  •  0
  •   dpollock    16 年前
    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);
    }
    
        12
  •  0
  •   Philibert Perusse    16 年前

    继续前面的回答,非常简单地遍历Split返回的数组并转换为一个新的int数组。下面的示例以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]);
            }
    
        13
  •  0
  •   Magnus Akselvoll    16 年前

    我认为最简单的方法是如前所示拆分,然后循环遍历这些值并尝试转换为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;
        }
    }