Reverse words

Reverse words in a sentence.  Eg:  "Hello world how are you?"  is converted to "you? are how world Hello"
/*
 * ReverseWords.cpp
 *
 *  Created on: Apr 11, 2012
 *      Author: Kiran Hegde
 */

#include <iostream>
#include <string>
#include <string.h>

using namespace std;

void reverseString(char *str, int start, int end) {
    char temp;
    while (start < end) {
        temp = str[start];
        str[start++] = str[end];
        str[end--] = temp;
    }
}

void reverseWords(char *words) {
    int len = strlen(words);
    // first reverse the entire sentence
    reverseString(words, 0, len - 1);
    // now reverse each word
    int start = 0;
    int end = 0;
    while (end < len) {
        start = end; //start of new word = end of last word
        //go to end of word
        while ((words[end] != ' ') && (end != len))
            end++;
        end--; //reached a whitespace. Go back one char.
        reverseString(words, start, end); //reverse the word
        end += 2; //go past the whitespace
    }
}

/**
 * Test the function
 */
int main() {
    string s = "How are you doing world? Are you okay?";
    char *sentence = new char[s.length() + 1];
    strcpy(sentence, s.c_str());
    sentence[s.length()] = '\0';
    cout << "Sentence: " << sentence << endl;
    reverseWords(sentence);
    cout << "Reversed: " << sentence << endl;
    delete[] sentence;
    return 0;
}
Comments