将一句话的单词进行倒置,标点不倒置。比如 I like beijing. 经过函数后变为(beijing. like I)


题目:将一句话的单词进行倒置,标点不倒置。比如 I like beijing. 经过函数后变为:beijing. like I
输入描述:
每个测试输入包含1个测试用例: I like beijing. 输入用例长度不超过100
输出描述:
依次输出倒置之后的字符串,以空格分割
NOWCODER.COM
牛客网·互联网名企笔试/面试题库
牛客出品-http://www.nowcoder.com
示例1:
输入
I like beijing.
输出
分析:先整体(字符串)逆置字符串,再局部(单词)逆置

先整体(字符串)逆置字符串,再局部(单词)逆置 void reverse_str(char* begin, char* end) { assert(begin); assert(end); while (begin < end) { char tmp = *begin; *begin = *end; *end = tmp; begin++; end--; } }void reverse_words(char* str, int len) { char* str1 = str; reverse_str(str1, str1+len-1); char* start = str1; //记录单词开头 char* finish = str1; //记录单词结尾 while (*str1 != '\0') { start = finish; while (!isspace(*str1) && *str1!='\0') { str1++; } //来到这说明一个单词完了,倒置单词 finish = str1 - 1; reverse_str(start, finish); if(*str1 != '\0') str1++; //str指向下一个单词开头finish = str1; } }

void reverse_words() { string s; getline(cin, s); //整体反转 reverse(s.begin(), s.end()); //单词局部反转 auto start = s.begin(); while (start != s.end()) { auto end = start; while (end != s.end() && *end != ' ') { end++; } reverse(start, end); if (end != s.end()) { start = end + 1; } else { start = end; } } cout << s << endl; }





【将一句话的单词进行倒置,标点不倒置。比如 I like beijing. 经过函数后变为(beijing. like I)】

    推荐阅读