Reverse words in a given string
STRINGS
Problem statement:
Given a String S, reverse the string without reversing its individual words. Words are separated by dots.
INPUT :
- Here, they have given string S as input, in which words are separated by dots.
OUTPUT:
- Should return reversed string without reversing the individual words in it which are separated by dots as well.
FOR EXAMPLE:
- INPUT = S = i.like.this.program.very.much
- OUTPUT =much.very.program.this.like.i
Some of the string functions that we are going to use here are as follows:
- size() — To find the size of the string.
- substr() — To find the part of the string from the given string, i.e. a sub-string.
- append() — To join the characters of a string at the end of another string.
SOLUTION:
Step 1:
- First we are going to find the size of the given string using size() function:
int n = S.size();
2.Then we are going to declare 2 variables of type int namely i(keep track of index) and r(to store number of characters in a word that are separated by dot) and a string S2.
int i; // To keep track of string index
string S2; // To store the reversed string step by step
int r; //To store number of character in a word
Step 2:
- Here, we are going to form the main loop here.We are going to traverse from last to first, since we have to reverse.The index keeps on decreasing until it encounters a dot.
for(i=n-1;i>=0;i- -)
if(S[i] == ‘.’)
2.So, when we encounter a dot, then we are going to make use of below codes:
r= n -i; // This gives the size of a word that have to append in the S2
n = i-1;//Gives remaining size of the string
S2.append(S.substr(i+1,r));
// This line basically appends r characters from (i+1)th position.
S2.append(“.”);
In the above diagram, we can see that we encounter dots at 1st , 6th and 11th position.As we are iterating from the end, we’ll encounter the 11th index “.” first.
So, when the loop encounters 11th index, it’ll append 8 characters from 12th index to S2 which is further appended with a “.” and similarly when the loop encounters 6th index,it’ll append 4 characters from the 7th index to S2 which is also appended with a “.” after that.
Step 3:
This is pretty short and easy step and you can call it step 2 it you want.As for the above example, after coming out of the loop, the value of n will be 0.
S2.append(S.substr(0,n+1)); // So it will append from 0 to remaining size of the string
return S2;
Here, we are going to append the last word of the reversed string S2 whose index actually starts with the 0th index of the input string S1.So it will append from 0 to remaining size of the string S1 to S2.(In n+1, 1 is added because the string indices start from 0)
And finally it returns the reversed S2 string.
I hope you guys, found this article useful and helpful and I would really appreciate if you could give your valuable feedback.Cheers!