Split a string using delimiter in C#
This post will discuss how to split a string in C# using a specified delimiter and convert it into a list of strings.
The idea is to use the String.Split() method to split a string with a specified delimiter. It returns a string array that contains the substrings delimited by elements of the specified string. To convert a string array into a list of strings, we can use any of the following methods.
1. Using Enumerable.ToList() method
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
using System; using System.Collections.Generic; using System.Linq; public class Example { public static void Main() { string str = "A,B,C,D,E"; char delim = ','; string[] values = str.Split(delim); List<string> list = values.ToList(); Console.WriteLine(String.Join(Environment.NewLine, list)); } } /* Output: A B C D E */ |
2. Using List Constructor
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
using System; using System.Collections.Generic; public class Example { public static void Main() { string str = "A,B,C,D,E"; char delim = ','; string[] values = str.Split(delim); List<string> list = new List<string>(values); Console.WriteLine(String.Join(Environment.NewLine, list)); } } /* Output: A B C D E */ |
3. Using List<T>.AddRange() method
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
using System; using System.Collections.Generic; public class Example { public static void Main() { string str = "A,B,C,D,E"; char delim = ','; string[] values = str.Split(delim); List<string> list = new List<string>(); list.AddRange(values); Console.WriteLine(String.Join(Environment.NewLine, list)); } } /* Output: A B C D E */ |
That’s all about splitting a string using delimiter in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)