用空格反转一个字符串

时间:2014-05-10 18:07:25

标签: c++ string reverse swap

我正在尝试编写一个用户反转字符串的c ++代码。 例如:

用户输入"apple and orange"

输出为"orange and apple"

#include <stdio.h>
#include <string.h>

int main(void) {

char str[100];

char delims[] = " ";
char *token;

printf("enter your word seperated by space ");
gets(str);
token = strtok( str, delims );
while ( token != NULL ) {
    printf( " %s\n", token);
    token = strtok( NULL, delims );

}
system("pause");
return 0;
}
问:我怎么能交换第一个和最后一个字? 感谢。

1 个答案:

答案 0 :(得分:0)

使用std::string

使用std::string::find查找单词的开头和结尾。

使用std::string::substr将单词复制到新字符串。

使用std::stack<std::string>包含字词。

将每个单词推入堆栈。

在句子结尾处:
流行词,打印词。

示例:

// Input the sentence.
std::string word;
std::string sentence;
cout << "Enter sentence: ";
cout.flush();
std::getline(cin, sentence);

// Search for the end of a word.
static const char letters[] = 
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "abcdefghijklmnopqrstuvwxyz";
std::string::size_type word_start_position = 0;
std::string::size_type word_end_position = 0;
word_end_position = sentence.find_first_not_of(letters);
word = sentence.substr(word_start_position, 
                       word_end_position - word_start_position);

// Put the word into a stack
std::stack<std::string> word_stack;
word_stack.push_back(word).  

此示例存在问题,但它显示了基本概念。

相关问题