为什么这个代码不反转句子中的单词?

Why is this code not reversing the words in a sentence?

本文关键字:句子 单词 代码 为什么      更新时间:2023-10-16

所以我想把一个句子中的单词翻转过来,而且只翻转这个单词。例如:

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

我做错了什么?

最好忘记这一切,用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;
}

strtok函数不会在一次调用中进行标记化。每次调用它时,它都会返回下一个令牌。请仔细阅读文档

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;
}

这是一个众所周知的问题,有一个简单的技巧(在适当的地方):

  1. 反转字符串
  2. 对于每个单词
    • 倒序

试题:

#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";
}

try this:

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;
}