Почему этот код не меняет слова в предложении? - PullRequest
0 голосов
/ 18 декабря 2011

Итак, я хочу взять слова в предложении и перевернуть слово, и только слово вокруг. Например:

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 ]

7 голосов
/ 18 декабря 2011

Лучше всего все забыть и вместо этого написать 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 голос
/ 18 декабря 2011

Функция strtok не токенизируется за один вызов. Он возвращает следующий токен каждый раз, когда вы вызываете его. Читайте документацию более внимательно.

0 голосов
/ 15 сентября 2012

попробуйте это:

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;
}
0 голосов
/ 18 декабря 2011

Это хорошо известный вопрос с простым приемом (чтобы сделать это на месте):

  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";
}
0 голосов
/ 18 декабря 2011
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;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...