Search code examples
c#.netstringsplit

splitting a string based on multiple char delimiters


I have a string "4,6,8\n9,4"

I want to split this based on ,and \n

Output array should be

4
6
8
9
4

Edit :

Now i am reading string from console , when i enter a string as above in console , in the code behind i get as "4,6,8\\n9,4" . Now that i want to split using "," and "\\n" . How can i change the expression ?


Solution

  • Use string.Split(char [])

    string strings = "4,6,8\n9,4";
    string [] split = strings .Split(new Char [] {',' , '\n' });
    

    EDIT

    Try following if you get any unnecessary empty items. String.Split Method (String[], StringSplitOptions)

    string [] split = strings .Split(new Char [] {',' , '\n' }, 
                                     StringSplitOptions.RemoveEmptyEntries);
    

    EDIT2

    This works for your updated question. Add all the necessary split characters to the char [].

    string [] split = strings.Split(new Char[] { ',', '\\', '\n' },
                                     StringSplitOptions.RemoveEmptyEntries);