你如何扭转字符串中单词(而不是字母)的顺序?

时间:2014-02-07 03:05:29

标签: c++

我如何改变字符串中单词的顺序?我尝试了这个,但它不起作用:

string sen = "Go over there";
reverse(sen.begin(), sen.end());

但这会颠倒整个字符串,但不会保持正确的单词。我如何只反转字符串中单词的顺序?

3 个答案:

答案 0 :(得分:1)

我之前写了很多这样的字符串函数:

// Make copy of this original if you don't wish to destroy in the process
string sen    = "Go over there";

// string that will become your reversed string
string newStr = new string();

// A temp variable that will hold the current position of the last separator character
int aChar     = -1;

////////////////////////////////////////////////////////////////////////////////////////
// You may want to delete pre and post spaces here
////////////////////////////////////////////////////////////////////////////////////////

// Loop through the entire string until the original is empty
while(sen.length > 0){
    // Find the last separator character (in your case a space) within the string
    aChar   = sen.find_last_of(" ");

    // Append the word created from one char forward of the last found separator char
    // to the end of the CURRENT version of the original string
    newStr += sen.substr(aChar + 1, sen.length - aChar - 1);

    // Store a new version of the original string that is the SUBSTRING from beginning (char 0)
    // to one char before the last found separator character
    sen     = sen.substr(0, aChar - 1);

    // Need to add the space between the words, but only if the new substring is not empty
    if(sen.length > 0) newStr += " ";
}

我还没有测试过这段代码,但是如果API按照预期的方式工作,那么算法就可以了。

作为API,这可能如下所示

string reverse(string inStr){
    // Make copy of the original so we don't destroy it in the process
    string sen    = inStr.copy();

    // string that will become your reversed string
    string newStr();

    // A temp variable that will hold the current position of the last separator character
    int aChar     = -1;

    ////////////////////////////////////////////////////////////////////////////////////////
    // You may want to delete pre and post spaces here
    ////////////////////////////////////////////////////////////////////////////////////////

    // Loop through the entire string until the original is empty
    while(sen.length > 0){
        // Find the last separator character (in your case a space) within the string
        aChar   = sen.find_last_of(" ");

        // Append the word created from one char forward of the last found separator char
        // to the end of the CURRENT version of the original string
        newStr += sen.substr(aChar + 1, sen.length - aChar - 1);

        // Store a new version of the original string that is the SUBSTRING from beginning
        // (char 0) to one char before the last found separator character
        sen     = sen.substr(0, aChar - 1);

        // Need to add the space between the words, but only if the new substring is not empty
        if(sen.length > 0) newStr += " ";
    }

    return newStr;
}

int main(int argc, char *argv[]){
    string sen = "Go over there";
    string rev = reverse(sen);
}

答案 1 :(得分:0)

如果字符串中的单词用空格分隔,您可以在string.find()循环中使用while来查找中断,然后使用string.substr()将单词输出到{ {1}}。然后你可以简单地向后阅读vector

答案 2 :(得分:0)

Live Example

如果您使用C ++ 11,sen.pop_back()将删除最后一个空格,否则您可以查看Remove last character from C++ string以获取其他示例。其次,我们只使用反向迭代器std::reverse(output.begin(), output.end())rbegin(),而不是rend()。 for循环可以明确改进,但它可以完成工作。

#include <sstream> 
#include <iterator> 
#include <algorithm>
#include <iostream>

using namespace std;
int main(int argc, char *argv[]) {
    std::vector<std::string> output;
    std::string sen = "Go over there";
    std::string word = "";
    unsigned int len = 0;
    for (const auto& c : sen) {
        ++len;
        if (c == ' ' || len == sen.size()) {
            if (len == sen.size())
                word += c;
            output.push_back(word);
            word = "";
        }
        if (c != ' ')
            word += c;
    }
    std::ostringstream oss;
    std::copy(output.rbegin(), output.rend(), std::ostream_iterator<std::string>(oss, " "));
    sen = oss.str();
    sen.pop_back(); // Get rid of last space, C++11 only
    std::cout << sen;
}