/****************************************************************************************** 用C++语言实现,将一句话中的单词进行倒置(单词之间倒转,单词本身不倒置),标点符号不导致。 比如一句话“I come from tianjin. “,倒置后变成“tianjin. from come I ”。 ******************************************************************************************/ //方法是:把字符串全部反转,然后再按单词遇到空格整个反转。 #include <iostream> #include<cstring> #include<string> using namespace std; string strReverse(string sourcestr) { int j = 0,i = 0,begin,end; string str = sourcestr; char temp; j = str.size() - 1; cout << " string = " << str << endl<< j<< endl; //先将字符串进行全部倒转 变成 .nijnaiT morf emoc I while (j > i){ temp = str[i]; str[i] = str[j]; str[j] = temp; j --; i ++; } cout << " string = " << str << endl; //然后进行按单词部分反转,遇到空格,则判断出一个单词结束 i = 0; while (str[i]){ if (str[i] != ' ') { //找到单词开始和截止的位置 begin = i; while (str[i] && str[i] != ' '){ end = i; i++; } if (str[i] == '\0'){ //字符串的结束符 i--; } } while (end > begin){ //交换停止判断 temp = str[begin]; str[begin] = str[end]; str[end] = temp; end --; begin ++; } i ++; } cout << " string = " << str << endl<< "i is " << i<< endl;//此时的i指向的是字符串最后一个 '\0' return str; } int main() { //string str = "I come from Tianjin."; string str; cout << "Please enter a sentences\n" ; getline(cin,str); strReverse(str); return 0; }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。