Reversing words in a String

Given a String, reverse the string but do not reverse the words. For example, if
 Input : "MCN Professionals is now Ritambhara"
 Output: "Ritambhara now is Professionals MCN"
Your function should not take more that O(n) time in the worst case.

Solution:

The solution to this problem is very simple, It uses the reverse algorithms. You can easily write a reverse function to reverse the entire string. Its logic will be like below:

For i = START to MID
    swap(str[i] , str (n-i))

Once, we have this reverse function then the algorithm to reverse the array word-wise will be as below:

Algorithm:
Step-1: Reverse entire string
Step-2: Reverse individual words in the string
For example:

Input:

"MCN Professionals is now Ritambhara"

Reverse the entire string

"arahbmatiR won si slanoisseforP NCM"

Now reverse individual words in the string

"Ritambhara now is MCN Professionals"
Code:

Let u first write the reverse function, which can reverse the part of a string (it take start & end position in a string)

    void reverse(char *str, int startpos, int endpos)
    {
        int i = startpos;
        int len = startpos + (endpos-startpos)/2;
        for (; i<len+1; i++)
        {
            char temp = str[i];
            str[i] = str[endpos-i + startpos];
            str[endpos-i + startpos] = temp;
        }
    }

Main function to reverse the string word-wise

    void reverseWords(char* str)
    {
        int len = strlen(str)-1;
        // reversing the Entire string.
        reverse(str, 0, len);
        int startpos = 0;
        int i = 0;
        while(i<=len)
        {
            i++;
            // If character is a white space or end of the string is reached
            if(str[i] == ' ' || str[i] == '\t' ||
                str[i] == '\n' || str[i] == '\0')
            {
                reverse(str, startpos, i-1);
                // updating i to point to the next non-space character
                while( (str[i] == ' ' || str[i] == '\t' ||
                        str[i] == '\n') && (str[i] != '\0') )
                    i++;
                startpos = i ;
            }
        }
    }

Tags:

String Reverse

0 Comments

Leave a comment