In this article, we will discuss different ways to convert a std:;string object to list of characters in C++.
Table Of Contents
Method 1: Using list constructor
In C++, the list class provides a constructor, which accepts a range as arguments i.e. iterators prointing to start and end location of a range. We can pass the start, and end iterators of string to this constructor, it will initialize the list object with the characters in string. Let’s see an example,
#include <iostream> #include <string> #include <list> int main() { std::string strValue = "Sample Text"; // Initialize a list with characters in string std::list<char> listOfChars(strValue.begin(), strValue.end()); // Print list content for(const char& ch: listOfChars) { std::cout << ch << ", "; } std::cout<<std::endl; return 0; }
Output:
S, a, m, p, l, e, , T, e, x, t,
We converted the string to list of characters.
Frequently Asked:
Method 2: Using STL Algorithm copy()
Create a list object. Then pass following arguments in the STL Algorithm copy().
- Iterator pointing to the start of string.
- Iterator pointing to the end of string
- A back inserter iterator of the list.
It will push all the string characters to the list. Let’s see an example,
#include <iostream> #include <string> #include <list> #include <algorithm> int main() { std::string strValue = "Sample Text"; // Create an empty list std::list<char> listOfChars; // Copy all characters from string to the list std::copy( strValue.begin(), strValue.end(), std::back_inserter(listOfChars)); // Print list content for(const char& ch: listOfChars) { std::cout << ch << ", "; } std::cout<<std::endl; return 0; }
Output:
S, a, m, p, l, e, , T, e, x, t,
We converted the string to list of characters.
Best Resources to Learn C++:
Method 3: Using for-loop
Create a list object. Then iterator over all characters in string using a for loop. During iterator, push each character to the list. Let’s see an example,
#include <iostream> #include <string> #include <list> int main() { std::string strValue = "Sample Text"; // Create an empty list std::list<char> listOfChars; // Iterate over all characters in string for(const char& ch: strValue) { // Add character to the list listOfChars.push_back(ch); } // Print list content for(const char& ch: listOfChars) { std::cout << ch << ", "; } std::cout<<std::endl; return 0; }
Output:
S, a, m, p, l, e, , T, e, x, t,
We converted the string to list of characters.
Summary
We learned about different ways to convert a string to list of characters in C++. Thanks.