How to convert a string to a vector of chars in C++

In this tutorial, we will learn how to convert a string to a vector of chars in C++. We will be learning about some functions of the string standard library and some functions of the vector standard library. The String type is used to store a sequence of characters.

How to convert a string to a vector of chars in C++

We will be taking a string as input and then creating a vector of char then we will use push_back() to insert char into vector. Also, check:

First, we will define a string named “str” and use it as our input. Then we will be defining a vector of characters named vec.

#include <bits/stdc++.h>
using namespace std;

int main(){

  string str="codespeedy";
  vector<char> vec;

 

We will be pushing its characters into vector using push_back() function. We will use a for loop to add the characters of the string into the vector one by one. Strings by default are indexed starting from zero.

for(int i=0;i<str.length();i++){
  vec.push_back(str[i]);
}

 

Now to check if the string is converted into vector of characters we will print the characters in the vector with a space in between to match with the input string.

for(int i=0;i<vec.size();i++){
  cout<<vec[i]<<" ";
}

 

Here is the full code:

#include <bits/stdc++.h>
using namespace std;

int main(){

  string str="codespeedy";
  vector<char> vec;

  for(int i=0;i<str.length();i++){
    vec.push_back(str[i]);
  }
  
  for(int i=0;i<vec.size();i++){
    cout<<vec[i]<<" ";
  }
}

 

Output:

c o d e s p e e d y 

Leave a Reply

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