0
How can I reverse string of words
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
+ 2
In which language..?
please mention tag of language..
+ 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;
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;
}