为什么这段代码没有颠倒句子中的单词?

时间:2011-12-17 20:08:15

标签: c++ string

所以我想用一个句子中的单词来翻转单词,只翻译单词。例如:

Hello there

将更改为:

olleH ereht

所以我尝试使用以下代码:

#include <iostream> //Include the necessary header files.
#include <string>
#include <vector>

int main (int argc, const char * argv[]) {

    std::string sentence("Hello this is a sentence"); //This is the sentence I want to convert.
    char *tokens = strtok(strdup(sentence.c_str()), " "); //Tokenize the sentence.

    std::string tempToken; //Will use this to store the tokens in reverse.
    std::vector< std::string > strings; //This will keep all contents of the converted sentence.

    for (int i = (int)sentence.length()-1; i >= 0; i--) { //Go through the sentence backwards.

        if (tokens[i] == NULL) { //If tokens[i] == NULL then that was a complete token.

            strings.push_back(tempToken); //Push back the reversed token.
            tempToken.clear(); //Clear the reversed token so it can be used again to store another reveresed token.

        }
        else { //Still in the middle of a token

            tempToken.append(&tokens[i]); //Since I am iterating backwards this should store the token backwards...

        }
    }
    for (std::vector<std::string>::reverse_iterator it = strings.rbegin(); it != strings.rend(); ++it) { //Because I used strings.push_back(tempToken) I need to go through the vector backwards to maintain the word placement.

        std::cout << *it; //Print the words backwards.

    }
}

基本上,我接受了一个判决。然后我将它标记出来。向后循环字符串并将字符存储在字符串中,直到我到达令牌的末尾。当我到达令牌的末尾时,我将刚刚存储的字符从向后循环中取出并将其放入向量中。然后在我用所有标记完成后,我打印出矢量的内容。

当我运行这个程序的句子时:

Hello this is a sentence

转换为:

ecenceencetencentenceentencesentence sentencea sentence a sentences a sentenceis a sentence is a sentences is a sentenceis is a sentencehis is a sentencethis is a sentence

我做错了什么?

5 个答案:

答案 0 :(得分:7)

最好忘记一切,改写C ++:

#include <string>
#include <sstream>
#include <iostream>

void reverse_words(std::string const & sentence)
{
    std::istringstream iss(sentence);
    std::string word;
    while (iss >> word)
    {
        std::cout << std::string(word.rbegin(), word.rend()) << " ";
    }
    std::cout << std::endl;
}

答案 1 :(得分:1)

strtok函数在一次调用中没有标记化。每次调用它时都会返回下一个标记。更仔细地阅读文档。

答案 2 :(得分:0)

void main(string s){
List<string> strings = new List<string>();
strings = s.split(" ").toList();
string backwards = "";
foreach(string str in strings){
   string stri = str;
   for(int i = 0; i< str.length(); i++){
    backwards += stri.substr(stri.length() - 1);
    stri = stri.substr(0,stri.length() -1);
   }
   backwards += " ";
}
cout << backwards;
}

答案 3 :(得分:0)

这是一个众所周知的问题,有一个简单的技巧(要做到这一点):

  1. 反转字符串
  2. 每个单词
    • 反转单词
  3. 尝试:

    #include <iostream>
    #include <string>
    
    int main()
    {
        //  Get the line
        std::string  line;
        std::getline(std::cin, line);
    
        // Reverse the whole line.
        std::reverse(line.begin(), line.end());
    
        // Find the start of the first word
        std::string::size_type beg = line.find_first_not_of(" \t");
    
        while(beg != std::string::npos)
        {
            // Find the end of the word we have found
            std::string::size_type end = line.find_first_of(" \t",beg);
            end = (end == std::string::npos ? line.size() : end);
    
            // Reverse the word
            std::reverse(&line[beg],&line[end]);
    
            // See if we can find the next word
             beg = line.find_first_not_of(" \t", end);
        }
    
        // Print the result.
        std::cout << line << "\n";
    }
    

答案 4 :(得分:0)

试试这个:

string reverseString(string inputStr){
    inputStr += ' ';
    int len = inputStr.size();
    len--;
    int j;
    for(int i=0;i<=len;i++){
        for( j=i ;inputStr[i] != ' ';i++);

      int ii=i;
      while(j<=ii){
      char temp = inputStr[ii];
      inputStr[ii] = inputStr[j];
      inputStr[j] = temp;
      j++;
      ii--;
      }
    }
return inputStr;
}