Search This Blog

Apr 22, 2014

c# - Convert comma separated string to array

Split separates strings. Often strings have delimiter characters in their data. Split handles splitting upon string and character delimiters.Methods can be combined. Using IndexOf and Substring together is another way to split strings.
Use Split to separate parts from a string. If your input is "A B C", split on the space to get an array of "A", "B" and "C".

string str = "1,2,3,4";

        // 1st way
        string[] strArray = str.Split(new char[] { ',' });
        int[] intArray = new int[strArray.Length];
        for (int i = 0; i < strArray.Length; i++)
            intArray[i] = int.Parse(strArray[i]);

        // 2nd way
        string[] array = str.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

1 comment:

Related Posts Plugin for WordPress, Blogger...