0

Hey guys I need a push in the right direction im confused on how to iterate through this string "feeenhpoorilumayngtumseatsdmepotositnsfrlerruepsrennurdaorantiedbeunrtioradarahe" frontwords and backwards a push in the right would be pleasent if anyone can help

4
Contributors
3
Replies
16
Views
2 Years
Discussion Span
Last Post by Petcheco
0

To iterate through a string is to conduct some operation on each char in turn.

So get the string:

string value = "feeenhpoorilumayngtumseatsdmepotositnsfrlerruepsrennurdaorantiedbeunrtioradarahe";

and then go through every char in turn

for (int i =0; i < value.length(); ++i)
{
  char currentChar = value[i];
  // do something with the char if you like
}
0

Then to do that backwards:

    for (int i = value.length()-1; i >= 0; i--)
    {
        char currentChar = value[i];
        // do something with the char if you like
    }
0

Hello, Fernando.

To iterate through a string from beginning to end you can use a for-loop together with the str.length() function, like this:

for (i = 0; i < str.length(); i++)
{
 cout << str[i] << endl;
}

To iterate backwards, all you have to do is change the conditions of the loop:

for (i = str.length() - 1; i >= 0; i--)
{
  cout << str[i] << endl;
}

Don't forget to add the <string> library and to use getline(cin, str) so that you can use spaces between words.

Petcheco.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.