March 16, 2012

Reverse the order of words in a string


Q: Write a C program to reverse the order of words in a string. For simplicity, space has been chosen as word delimiter and punctuation is considered part of the word.


Example: 
Input: Can you reverse the words in this string.
Output: string. this in words the reverse you Can


Time Complexity: O(log(n))


void reverse_word(char *word, int length)
{
    int start;
    int end = length - 1;
    char temp;


    for (start = 0; start < end; start++, end--) {
        temp = word[start];
        word[start] = word[end];
        word[end] = temp;
    }
}


void reverse_string(char *string)
{
    int index;
    int string_length = strlen(string);
    int word_start_index = 0;
    int word_length = 0;


    // Reverse the original string
    reverse_word(string, string_length);


    for (index = 0; index < string_length; index++) {
        // found word delimiter
        if (string[index] == ' ') {
            reverse_word(&string[word_start_index], word_length);
            word_length = 0;
            word_start_index = index + 1;
        } else {
            word_length++;
        }
    }


    // Reverse the last word
    if (word_length) {
        reverse_word(&string[word_start_index], word_length);
    }
}

1 comment:

  1. I just wrote this one: found that logic is same as yours. its just little less code:

    //reverse letters in a string
    //so the becomes eth or "the words" becomes "sdrow eht"
    void reverseString(char * str, int b, int e)
    {
    while(b<e)
    {
    char temp = str[e];
    str[e] = str[b];
    str[b] = temp;
    e--;
    b++;
    }
    }

    //reverse all words in the string
    //so the "The words are" become "are words The"
    void reverseWords(char* str)
    {
    int b = 0, e =0, len;
    len = strlen(str);
    reverseString(str,0, strlen(str)-1);
    while( e <= len)
    {
    if(str[e] == ' ' || e==len)
    {
    reverseString(str,b,e-1);
    b = e+1;
    }
    e++;
    }
    }
    int main()
    {
    char str[] = "The words are required to be reversed.";
    reverseWords(str);
    cout<<"str= "<<str<<endl;
    }

    ReplyDelete