+ 2

How to reverse a given string in c++

Reverse the given string

30th Sep 2021, 5:19 PM
Nagaraj Arjun
Nagaraj Arjun - avatar
7 Respostas
+ 3
// A Simple C++ program to reverse a string #include <bits/stdc++.h> using namespace std; // Function to reverse a string void reverseStr(string& str) { int n = str.length(); // Swap character starting from two // corners for (int i = 0; i < n / 2; i++) swap(str[i], str[n - i - 1]); } // Driver program int main() { string str = "geeksforgeeks"; reverseStr(str); cout << str; return 0; }
30th Sep 2021, 5:53 PM
Arun Jamson
Arun Jamson - avatar
+ 2
One of many possible ways is 1.to copy the string to a placeholder. 2.go through reversed loop from the last element to the beginning of the string ... copy characters to the placeholder while doing this. 3.copy the placeholder to the original string .
30th Sep 2021, 5:32 PM
‎وائل عبد الحق‎
‎وائل عبد الحق‎ - avatar
+ 2
Thanks a lot❤️
30th Sep 2021, 5:36 PM
Nagaraj Arjun
Nagaraj Arjun - avatar
+ 2
Can you give a small example with this reverse string....it will be very helpful for me .
30th Sep 2021, 5:38 PM
Nagaraj Arjun
Nagaraj Arjun - avatar
+ 2
ok , Nagaraj Arjun here's an example : string org = "012345678"; //index start at zero int rlen = org.length() - 1; string placeholder(len,len); for(int x = rlen ; x >= 0; --x) { //(rlen = 8 , x = 8 ) = 0 , so on ..etc placeholder[rlen-x] = org[x]; } org = placeholder; cout<<org<<endl; if you find this answer useful please mark it ✔️
30th Sep 2021, 5:59 PM
‎وائل عبد الحق‎
‎وائل عبد الحق‎ - avatar
+ 2
Once again thank you❤️❤️.It was very helpful ❤️
1st Oct 2021, 4:47 AM
Nagaraj Arjun
Nagaraj Arjun - avatar