Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through string char by char

Tags:

c++

I try to iterate through a string char by char. I tried something like this:

void print(const string& infix)
{
char &exp = infix.c_str();
while(&exp!='\0')
{
         cout<< &exp++ << endl;
    }
}

So this function call print("hello"); should return:

h
e
l
l
o

I try using my code, but it doesn't work at all. btw the parameter is a reference not a pointer. Thank you

like image 662
user1988385 Avatar asked Feb 03 '13 00:02

user1988385


3 Answers

Your code needs a pointer, not a reference, but if using a C++11 compiler, all you need is:

void print(const std::string& infix)
{
    for(auto c : infix)
        std::cout << c << std::endl;
}
like image 129
Mark Tolonen Avatar answered Oct 19 '22 23:10

Mark Tolonen


for(unsigned int i = 0; i<infix.length(); i++) {
    char c = infix[i]; //this is your character
}

That's how I've done it. Not sure if that's too "idiomatic".

like image 31
Dhaivat Pandya Avatar answered Oct 20 '22 00:10

Dhaivat Pandya


If you're using std::string, there really isn't a reason to do this. You can use iterators:

for (auto i = inflix.begin(); i != inflix.end(); ++i) std::cout << *i << '\n';

As for your original code you should have been using char* instead of char and you didn't need the reference.

like image 22
David G Avatar answered Oct 19 '22 22:10

David G