单词反转

来源:互联网 发布:清华 网络空间安全 编辑:程序博客网 时间:2024/04/30 09:09
/*单词反转  "I  am a student." -->  "student. a am I"*/#include <iostream>#include <iomanip>#include <limits>using namespace std;int main(int argc, char** argv){//*char str[] = "I am a student of BeiHang";int sz = sizeof(str);char* tp = new char[sz];int ps, pe;int pos;int ipos = 0;int nsz = 0;  // 记录复制子串的位置pos = sz - 2;while(pos >= 0){pe = pos; // 单词的末位置// 找空格{到行首时找不到空格,转到下一步}while(str[pos] != ' ' && pos > 0){ --pos;}// 如果当前位置是行首,则当前单词的起始位置为0, 否则,当前位置是空格,则单词的位置是当前位置加1if(pos == 0){  ps = 0;}else{ps = pos + 1;}// 复制找到的字串for( ipos = 0; ipos <= pe - ps; ++ipos){  tp[ipos + nsz] = str[ps+ipos];}tp[ipos + nsz] = ' ';// 拷贝完单词,添加一个空格ipos += 1;nsz = nsz  + ipos;   // 下一个单词的拷贝起始位置--pos;}tp[sz] = '\0';// 添加字符数组结束标志cout << tp << endl;return 0;}