HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Reversing every word in a string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
wordreversingeverystring

Problem

Examples:

char test1[] = "               ";
char test2[] = "   hello  z";
char test3[] = "hello world   ";
char test4[] = "x y z ";


Results:

"               "
"   olleh  z"
"olleh dlrow   "
"x y z "


The problem:


Reverse every world in a string, ignore the spaces.


The following is my code. The basic idea is to scan the string, when
finding a word, then reverse it. The complexity of the algorithm is
O(n), where n is the length of the string.

Could anyone help me verify it? Is there any better solution?

void reverse_word(char* s, char* e)
{
    while(s < e)
    {
        char tmp = *s;
        *s = *e;
        *e = tmp;
        ++s;
        --e;
    }
}

char* word_start_index(char* p)
{
    while((*p != '\0') && (*p == ' '))
    {
        ++p;    
    }

    if(*p == '\0')
        return NULL;
    else
        return p;
}

char* word_end_index(char* p)
{
    while((*p != '\0') && (*p != ' '))
    {
        ++p;
    }

    return p-1;
} 

void reverse_string(char* s)
{
    char* s_w = NULL;
    char* e_w = NULL;
    char* runner = s;

    while(*runner != '\0')
    {
        char* cur_word_s = word_start_index(runner);
        if(cur_word_s == NULL)
            break;
        char* cur_word_e = word_end_index(cur_word_s);
        reverse_word(cur_word_s, cur_word_e);
        runner = cur_word_e+1;    
    }
}

Solution

If using C++ is an option for you (which your tags suggest), then you might consider using std::swap for swapping the characters. You might also want to use isspace to check for whitespace other than ' '.

You could also write it all in a single function:

void reverse_every_word(char* s)
{
    char* front;
    char* back;
    while(*s != '\0')
    {
        // handle whitespace
        while(*s != '\0' && isspace(*s))
            s++;

        // skip to the end of the current word
        front = s;
        while(*s != '\0' && !isspace(*s))
            s++;

        // reverse
        back = s-1;
        while (front < back)
            std::swap(*front++, *back--);
    }
}

Code Snippets

void reverse_every_word(char* s)
{
    char* front;
    char* back;
    while(*s != '\0')
    {
        // handle whitespace
        while(*s != '\0' && isspace(*s))
            s++;

        // skip to the end of the current word
        front = s;
        while(*s != '\0' && !isspace(*s))
            s++;

        // reverse
        back = s-1;
        while (front < back)
            std::swap(*front++, *back--);
    }
}

Context

StackExchange Code Review Q#17517, answer score: 5

Revisions (0)

No revisions yet.