题目:将一句话里的单词进行倒置,标点符号不倒换。比如一句话"To be or not to be, just to find to try." 倒置后变成"try. to find to just be, to not or be To"。
参考《程序员面试宝典》所写:
#include <iostream>
#include <string>
using namespace std;
//将整句话进行倒置,标点符号不倒换
void reverString(char *str){
int j=strlen(str)-1;
int i=0;
while (i<j)
{
char tmp=str[i];
str[i]=str[j];
str[j]=tmp;
i++;
j--;
}
}
//按单词倒置
void reverWord(char *str){
int i=0;
int begin=0;
int end=0;
while (str[i])
{
//通过空格判断单词,记录每个单词的开头和结尾的位置,再进行倒置
if (str[i]!=' ')
{
begin=i;
while (str[i]!=' '&&str[i])
i++;
i=i-1;
end=i;
}
while (begin<end)
{
char tmp=str[begin];
str[begin]=str[end];
str[end]=tmp;
begin++;
end--;
}
i++;
}
}
int main(){
char p[]="To be or not to be, just to find to try.";
cout << "String:" << p << endl;
reverString(p);
cout << "Rever String:" << p << endl;
reverWord(p);
cout << "Rever Word:" << p << endl;
return 0;
}