这题目是一个同学面SAP的时候问的,题目很比较简单,给你一个string,eg: my book is good 然后要求把每个单词都颠倒顺序输出。 output::ym koob si doog;
最简单的思路肯定是先写一个对于一个不含空格的单词的颠倒程序,然后遇到一次空格调用一次,最后拼起来。
那如果题目要求你把单词颠倒呢?应该怎么写? output: good is book my; 所以我写了一个通用版。PS:好像程序题就问了这么一个,不过是QA实习生,简单也是肯定的。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string tmp;
string s = "my book is good";
int i = 0, j = 0;
while (s[i] != '\0'){
if (s[i] == ' '){
tmp = s.substr(j, i - j) + " " + tmp;
j = i + 1;
}
i++;
}
tmp = s.substr(j, i - j) + " " + tmp;
for(int i = tmp.size() - 2; i >=0; i--) //这里的循环语句如果注释掉,直接cout << tmp; 就可以输出第二种问题。
cout << tmp[i]; //这里减2是之前多加了个空格,可以在前面的tmp构造是避免,懒得改了。
}