【问题标题】:Reverse a string with spaces [duplicate]用空格反转字符串[重复]
【发布时间】:2014-05-10 18:07:25
【问题描述】:

我正在尝试编写一个 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;
}

问:如何交换第一个词和最后一个词? 谢谢。

【问题讨论】:

  • 这是一篇内容丰富的帖子,但毫无疑问。
  • 你的问题是?
  • 如何使用循环来反转字符串??
  • @user3435095 提示:您不需要反转字符串,而是反转单词的顺序! (并且不要使用strtok() BTW,它弊大于利)
  • 您想只交换第一个词和最后一个词,还是全部颠倒?我会使用 std::string 而不是 c 字符串,因为它有一些有用的功能,例如 find、find_last_of、substr 等,在这里可以提供帮助

标签: c++ string reverse swap


【解决方案1】:

使用std::string

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

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

使用std::stack&lt;std::string&gt; 包含单词。

将每个单词推入堆栈。

句末:
流行词,打印词。

示例:

// 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).  

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

【讨论】:

  • 我不是 c++ 程序员,请给我看看代码吗? @ThomasMatthews
  • @user3435095:更新了答案。还有其他技术可以提取单词,例如使用std::istringstreamstd::getline。但是,std::getline 只允许一个分隔符来标记单词的结尾,并且有更多的字符可以标记单词的结尾,如此注释所示。
猜你喜欢
  • 2017-06-21
  • 2011-09-27
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-02
  • 1970-01-01
相关资源
最近更新 更多