Split out ints from string

前端 未结 13 1356
情歌与酒
情歌与酒 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:28

    I think the easiest way is to split as shown before, and then loop through the values and try to convert to 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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题