c++ - 反转字符串中的每个单词(应该处理空格)

标签 c++ c string

例子:

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

结果:

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

问题:

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 != '\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;
    }
}

最佳答案

您的代码似乎是正确的,但它是普通的 C。在 C++ 中,使用相同的方法,它可能看起来像这样:

#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 <<'\n';
}

关于c++ - 反转字符串中的每个单词(应该处理空格),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12879348/

相关文章:

javascript - 将数组值与字符串进行比较

c - short int 和 unsigned short 的输出?

c - Malloc双指针

从范围返回模式字符串的java方法

c++ - RapidXML 打印头有未定义的方法

c - gtk_adjustment_get_value 段错误

java - 如何在 Java 中比较字符串?

C++:二进制搜索字符串的一部分

c++ - Boost 包含了严重破坏——但这不是 Boost 的错

c++ - 如何从 CGAL 中的坐标和拓扑列表创建 Polyhedron_3 数据结构