Split out ints from string

前端 未结 13 1346
情歌与酒
情歌与酒 2021-01-17 17:45

Let\'s say I have a web page that currently accepts a single ID value via a url parameter:
http://example.com/mypage.aspx?ID=1234

I want to change it to acce

相关标签:
13条回答
  • 2021-01-17 18:01
    List<int> convertIDs = new List<int>;
    string[] splitIds = ids.split(',');
    foreach(string s in splitIds)
    {
        convertIDs.Add(int.Parse(s));
    }
    

    For completeness you will want to put try/catches around the for loop (or around the int.Parse() call) and handle the error based on your requirements. You can also do a tryparse() like so:

    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);
    }
    
    0 讨论(0)
  • 2021-01-17 18:03

    Final code snippet that takes what I hope is the best from all the suggestions:

    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
    

    I was hoping to be able to do it in one or two lines of code inline. One line to create the string array and hopefully find something in the framework I didn't already know to handle importing it to a List<int> that could handle the cast intelligently. But if I must move it to a method then I will. And yes, I'm using VB. I just prefer C# for asking questions because they'll get a larger audience and I'm just about as fluent.

    0 讨论(0)
  • 2021-01-17 18:04

    You can instantiate a List<T> from an array.

    VB.NET:

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

    This is prone to casting errors though if the array contains non-int elements

    0 讨论(0)
  • 2021-01-17 18:06

    To continue on previous answer, quite simply iterating through the array returned by Split and converting to a new array of ints. This sample below in 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]);
            }
    
    0 讨论(0)
  • 2021-01-17 18:10

    split is the first thing that comes to mind, but that returns an array, not a List; you could try something like:

    
    List<int> intList = new List<int>;
    
    foreach (string tempString in ids.split(',')
    {
        intList.add (convert.int32(tempString));
    }
    
    
    0 讨论(0)
  • 2021-01-17 18:12

    You can use string.Split() to split the values once you have extracted them from the URL.

    string[] splitIds = ids.split(',');
    
    0 讨论(0)
提交回复
热议问题