0

How can I reverse string of words

1st Jul 2022, 11:03 PM
Jerry-Dan
Jerry-Dan - avatar
4 Antworten
+ 6
Jerry-Dan Algorithm to reverse a string: Step 1. Start Step 2. Read the string from the user Step 3. Calculate the length of the string Step 4. Initialize rev = “ ” //empty string Step 5. loop through the string but in reverse order Initialize i = length - 1 //start Repeat until i>=0: //end rev = rev + Character at position 'i' of the string i = i – 1 // increment Step 7. Print rev Step 9. Stop
1st Jul 2022, 11:17 PM
Aly Alsayed
Aly Alsayed - avatar
+ 2
In which language..? please mention tag of language..
2nd Jul 2022, 2:28 AM
Mihir Lalwani
Mihir Lalwani - avatar
+ 1
You can follow it in C++ 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]); cout << str;
2nd Jul 2022, 3:46 PM
Oleh Davydenko
Oleh Davydenko - avatar
0
in C++ you can do using pointers, it`s fun and simple #include<iostream> #include<cstring> using namespace std; int main() { char str[] = "I love to code in C++"; //The string char* q;//declare a char pointer int i = strlen(str);//get string lenght //starting from last character while (q=strchr(str, *(str + i - 1))) { cout << *q; // print.... i--; // ....one by one down } } If you want to store the string in to another variable you can modify a little bit like this.. #include<iostream> #include<cstring> using namespace std; int main() { char str[] = "I love to code in C++"; char rev[100] = { NULL }; char* q; int i = strlen(str); int j = 0; while (q=strchr(str, *(str + i - 1))) { *(rev+j) = *q; i--; j++; } cout << rev; }
12th Jul 2022, 7:47 PM
Adrian Bumbu
Adrian Bumbu - avatar