Итак, я хочу взять слова в предложении и перевернуть слово, и только слово вокруг. Например:
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
Что я делаю не так?