-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

user3746711
  • 45
  • 1
  • 3
  • 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,683
  • 2
  • 23
  • 37
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,562
  • 10
  • 38
  • 54
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
  • 11,026
  • 5
  • 30
  • 49