Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative for a loop in C++

I want to reverse a string without the use of a loop. My code with the loop looks like:

#include <iostream>
#include <string>

using namespace std;

string reverseString(string str) {
    string changedString;
    int strLength = int(str.length() - 1);
    for(int i {strLength}; i >= 0; i--) {
        changedString.push_back(str.at(i));
    }
    return changedString;
}

int main() {

    string str;

    cout << "Enter a string to reverse it:\n" << flush;
    cin >> str;
    cout << reverseString(str) << flush;
} 

Now I need to write a function without the loop. Only the methods of String should be used. Can you help me solving this problem?

like image 595
tiq Avatar asked May 15 '26 16:05

tiq


1 Answers

It is very simple to write such a function

std::string reverse( const std::string &s )
{
    return { s.rbegin(), s.rend() };
}

Here is a demonstrative program

#include <iostream>
#include <string>

std::string reverse( const std::string &s )
{
    return { s.rbegin(), s.rend() };
}

int main() 
{
    std::string s( "Hello World" );

    std::cout << s << '\n';
    std::cout << reverse( s ) << '\n';

    return 0;
}

Its output is

Hello World
dlroW olleH
like image 185
Vlad from Moscow Avatar answered May 18 '26 05:05

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!