Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

c++ - Reverse every word in a string (should handle space)

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.

How do verify it? Is there a 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 != '') && (*p == ' '))
    {
        ++p;
    }

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

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

    return p-1;
}

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

    while (*runner != '')
    {
        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;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your code seems correct, but it's plain C. In C++, using the same approach, it could look something like this:

#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>
#include <cctype>

int main()
{
    std::string str = "    cat cow dog wolf     lobster";
    std::string result;
    auto it = str.begin();

    while (it != str.end()) {

        while (it != str.end() && isspace(*it)) {
            result += *it;
            ++it;
        }

        auto begin = it;
        while (it != str.end() && !isspace(*it)) {
            ++it;
        }
        auto end = it;

        result.append(std::reverse_iterator<decltype(end)>(end),
                      std::reverse_iterator<decltype(begin)>(begin));

        // if you want to modify original string instead, just do this:
        std::reverse(begin, end);
    }

    std::cout << result <<'
';
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...