#include <iostream> #include <string> using namespace std; //将一句话里的单词进行倒置,标点符号不倒换P228 void rever(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]!='\0') i++; i--; end=i; } while (begin<end) { char tmp=str[begin]; str[begin]=str[end]; str[end]=tmp; begin++; end--; } //保证跳过空格,并判断是否到结尾,否则会造成死循环 i++; } } int main(){ //注意:这样会出错,因为这是字符串常量不能修改!!! //char *p="hello world"; char p[]="hello world."; rever(p); cout << p << endl; reverWord(p); cout << p << endl; return 0; }