How to reverse a string in C++?

by schuyler.moore , in category: C/C++ , 2 years ago

How to reverse a string in C++?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by edison.lang , a year ago

@schuyler.moore You can use the reverse() function to reverse any string in C++. See the code below as an example:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#include<iostream>
#include<algorithm>

int main() {
    std::string str = "test string";
    reverse(str.begin(), str.end());

    // Output: gnirts tset
    std::cout << str;
    
    return 0;
}


Member

by khalid , a year ago

@schuyler.moore 

To reverse a string in C++, you can use the reverse function from the algorithm library.


Here is an example code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
   string str = "Hello World!";
   reverse(str.begin(), str.end());
   cout << str << endl;
   return 0;
}


In this code, we first declare a string str with the value "Hello World!". Then we use the reverse function to reverse the string. The reverse function takes two arguments - the beginning and end iterators of the string. In this case, we use str.begin() as the beginning iterator and str.end() as the end iterator.


After the reverse function is called, the string str will be reversed. Finally, we print the reversed string using the cout statement.


The output of this code will be:

1
!dlroW olleH