Convert a string to a vector of chars in C++

In this article, we will discuss different ways to convert a string to a vector of chars in C++.

Table Of Contents

Method 1: Using Vector’s range constructor

Create two iterators pointing to the first, and one past the last characters of string. Then pass them to the range based constructor of vector, while creating a vector object. It will populate the vector of chars, with all the characters of the string. Let’s see an example,

#include <iostream>
#include <vector>
#include <string>

template <typename T>
void display(std::vector<T> vectorObj)
{
    // Iterate over all elements of vector
    for(auto& elem : vectorObj)
    {
        std::cout<<elem << ", ";
    }
    std::cout<<std::endl;
}

int main()
{

    std::string strValue = "Sample String";

    // Create a vector of chars from a string
    std::vector<char> vectorOfChars(strValue.begin(), strValue.end());

    display(vectorOfChars);

    return 0;
}

Output:

S, a, m, p, l, e,  , S, t, r, i, n, g, 

It converted the string to a vector of chars.

Method 2: Using copy() function

Pass two iterators pointing to the first, and one past the last characters of string to the copy() function, as a range. Also, pass a back_insert_iterator of vector object to the copy() function. It will copy all the characters of string to the vector of chars. Let’s see an example,

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

template <typename T>
void display(std::vector<T> vectorObj)
{
    // Iterate over all elements of vector
    for(auto& elem : vectorObj)
    {
        std::cout<<elem << ", ";
    }
    std::cout<<std::endl;
}

int main()
{
    std::string strValue = "Sample String";

    std::vector<char> vectorOfChars;

    // Add all characters of string to vector
    std::copy(
        strValue.begin(),
        strValue.end(),
        std::back_inserter(vectorOfChars));

    display(vectorOfChars);

    return 0;
}

Output:

S, a, m, p, l, e,  , S, t, r, i, n, g, 

It converted the string to a vector of chars.

Summary

We learned about different ways to convert a string to a vector of chars in C++.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top