Monday, January 14, 2013

Reverse a string by words

Wow! Accidentally created a nice code to reverse a string by words. Reversing a string is easy, but the problem arises when we have to reverse the word positions.

Target: This is a good string => string good a is This
Strategy: Simply reverse the whole string and then reverse each word
Code:
    char str1[] = "This is a good string";
    size_t j = strlen(str1)-1;
    //Step to reverse the whole string
    for (size_t i=0; i
        swap(str1[i],str1[j]);
    }

    //Step to reverse each word, word by word
    stack stk;
    for (size_t i=0; i<=strlen(str1); ++i){
        if ( (str1[i] != ' ') && (str1[i] != '\0')  )
            stk.push(str1[i]);
        else {
            while(!stk.empty()){
                cout<
                stk.pop();
            }
            cout<<" ";
        }
    }