Lets Learn together... Happy Reading

" Two roads diverged in a wood, and I,
I took the one less traveled by,
And that has made all the difference "-Robert Frost

Reverse the words position in a string


This can be done in two ways.
First Method:
 a.Find the length of the string
 b. Use MATLAB built in function strtok to separate the first word and the remaining sentence.
For instance, the input string is ‘Lets Learn together... Happy Reading’.
[Token,remain]=strtok(input_string);
The variable token will contain ‘Lets
And the variable remain will contain ‘Learn together… Happy Reading’.
Use while loop to extract all the strings.

c. In the first iteration, the string in the token variable is concatenated with a empty variable ‘t’.
Now t has ‘Hello’.
In the second iteration, token has ‘Learn’ and remain has ‘together… Happy Reading’.
Now the string ‘Learn’ is concatenated with the string t.

d. Here to preserve the space ,the syntax [string2, ‘  ’,string1] is used.
The length of the input_string gets reduced during each iteration and finally when all the strings are extracted, the loop is terminated.

MATLAB CODE:
%To reverse the words position in a string
str='Lets Learn together... Happy Reading';
%str=fliplr(str);
len=length(str);
t='';

 while(len>0)
     [token,str]=strtok(str);
     len=length(str);
     %token=fliplr(token);
     %t=[token,' ',t];
     t=[' ',token,t];
        
 end
 display(t);


Output:

t =

 Reading Happy together... Learn Lets



Second  Method:

This  differs  in the way of concatenation.
The input string position is reversed. And inside the loop after extracting each token, it is again reversed.
Then  the  string ‘t’ is concatenated with the token. The first method itself sufficient and just know the other way also.
like button Like "IMAGE PROCESSING" page

0 comments:

Enjoyed Reading? Share Your Views

Previous Post Next Post Home
Google ping Hypersmash.com