Convert a std::string to a std::list of chars in C++
This post will explore how to convert a std::string to a std::list of chars in C++.
1. Naive Solution
A naive solution is to use a range-based for-loop or the standard loop to push_back all characters of the std::string individually to the std::list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <iostream> #include <string> #include <list> int main() { std::string str = "ABC"; // list of characters std::list<char> chars; for (char c: str) { chars.push_back(c); } // print list for (char c: chars) { std::cout << c << std::endl; } return 0; } |
Output:
A
B
C
2. Using Range Constructor
The recommended approach is to use the range constructor of the list class, which takes two input iterators. For converting a std::string to std::list of chars, we have to pass the input iterator to the beginning and the end of the std::string, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <string> #include <list> int main() { std::string str = "ABC"; std::list<char> chars(str.begin(), str.end()); for (char c: chars) { std::cout << c << std::endl; } return 0; } |
Output:
A
B
C
3. Using std::copy function
Another good alternative is to use the standard algorithm std::copy for copying characters of the std::string to the end of a std::list using std::back_inserter, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <list> #include <string> int main() { std::string s = "ABC"; std::list<char> chars; std::copy(s.begin(), s.end(), std::back_inserter(chars)); for (char c: chars) { std::cout << c << std::endl; } return 0; } |
Output:
A
B
C
The std::back_inserter internally uses std::push_back function. If std::list has sufficient memory to accommodate all characters of the std::string, we can even pass the input iterator to the beginning of std::list:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <list> #include <string> int main() { std::string s = "ABC"; std::list<char> chars(s.length()); std::copy(s.begin(), s.end(), chars.begin()); for (char c: chars) { std::cout << c << std::endl; } return 0; } |
Output:
A
B
C
That’s all about converting a std::string to a std::list of chars 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 :)