腾讯2016年4月2号暑假实习移动开发岗的笔试题,编程题第四题大概题目是:
将一句话中的单词进行倒置(单词之间倒转,单词本身不倒置),标点符号不倒置。
比如一句话“I come from China.”,倒置后变成“China. from come I”。
C++的参考代码如下:
方法一:
#include <iostream> #include <string> using namespace std; //将句子按字符反转 void rever(string &str){ int j = str.length() - 1; int i = 0; while (i<j) { char tmp = str[i]; str[i] = str[j]; str[j] = tmp; i++; j--; } } //将句子的单词按字符反转 void reverWord(string &str){ int i = 0; int begin = 0; int end = 0; while (str[i]) { //标识出每个单词的开头和结尾的位置,之后进行逆转 if (str[i] != ' ') { begin = i; while (str[i] != ' '&&str[i] != '\0') i++; i--; end = i; } while (begin<end) { char tmp = str[begin]; str[begin] = str[end]; str[end] = tmp; begin++; end--; } //保证跳过空格,并判断是否到结尾,否则会造成死循环 i++; } } int main(){ string line; getline(cin,line); rever(line);//先将句子按字符反转 //cout << line << endl; reverWord(line);//再将句子的单词按字符反转 cout << line << endl; return 0; }
#include<iostream> #include<stack> #include<string> #include<sstream> using namespace std; int main(void) { stack<string> sstack; string line,word; getline(cin,line); istringstream stream(line);//字符输入流 while (stream >> word) { sstack.push(word); } while (!sstack.empty()) { cout << sstack.top() << " "; sstack.pop(); } cout << endl; return 0; }
运行结果: