-1

As the title says, how can I seperate a string into individual characters in c++? For example, if the string is "cat" how can I separate that into the characters c,a, and t?

Thanks

  • 2
    what do you want to do with the characters? They are already separate inside the string, you can access them at will. – Kerrek SB Nov 29 '14 at 16:35

3 Answers3

0

By using the operator[]. e.g.

std::string cat{"cat"};
if(cat[0] == 'c')
    //stuff
NaCl
  • 2,573
  • 2
  • 22
  • 36
0

If you're using std::string you can simply use .c_str( ) that will give you an array of the chars.

In c++11 you could also do:

for( auto c : a )
{
    cout << c << '\n';
}

http://ideone.com/UAyxTo

deW1
  • 5,364
  • 10
  • 40
  • 53
0

If you want to store them in a vector:

string str("cat");
vector<char> chars(str.begin(), str.end());

for (char c : chars)
    cout << c << endl;
w.b
  • 10,668
  • 5
  • 27
  • 47