Convert a String to a List of Chars in C#
This post will discuss how to convert a String to a List of characters in C#.
1. Using List.AddRange() Method
A simple solution is to use the List.AddRange() method to add all characters of a string to the end of an “existing” list. To get a List<char>, do like:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Collections.Generic; public class Example { public static void Main() { string str = "ABCDE"; List<char> chars = new List<char>(); chars.AddRange(str); Console.WriteLine(String.Join(", ", chars)); // A, B, C, D, E } } |
If you need a List<string> instead to store the characters, convert each character to a string first:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { string str = "ABCDE"; List<string> chars = new List<string>(); chars.AddRange(str.Select(c => c.ToString())); Console.WriteLine(String.Join(", ", chars)); // A, B, C, D, E } } |
2. Using List Constructor
Alternatively, you can use the List constructor to initialize a new instance of the List<char> class with characters of a string. You can simply pass a string to the list constructor, as the following example illustrates:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Collections.Generic; public class Example { public static void Main() { string str = "ABCDE"; List<char> chars = new List<char>(str); Console.WriteLine(String.Join(", ", chars)); // A, B, C, D, E } } |
If you want a list of strings, then you would use a List<string> rather than List<char>. To get a List<string>, transform each character to a string first:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { string str = "ABCDE"; List<string> chars = new List<string>(str.Select(c => c.ToString())); Console.WriteLine(String.Join(", ", chars)); // A, B, C, D, E } } |
3. Using Enumerable.ToList() Method
The Enumerable.ToList() method creates a List<T> from an IEnumerable<T>. It can be used to get a list of characters from a string, as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { string str = "ABCDE"; List<char> chars = str.ToList(); Console.WriteLine(String.Join(", ", chars)); // A, B, C, D, E } } |
That’s all about converting a String to a List of characters 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 :)