题目:输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。句子中单词以空格符隔开。为简单起见,标点符号和普通字母一样处理。
例如输入“I am a student.”,则输出“student. a am I”。
用了stl里的string类,方法是利用空格分析单词,从后往前遍历。写的比较笨拙.....
//翻转句子中单词的顺序 #include<iostream> #include<string> using namespace std; typedef string::size_type st; string myReverse(string sub){ //cout<<sub<<endl; string s; s.resize(sub.size()); for(st i=0;i<sub.size();i++) s[i]=sub[sub.size()-1-i]; return s; } string toReverseString(string line){ st start=0; string ans; for(st i=0;i<line.size();){ if(line[i]==' ') { if(!ans.empty()) ans+=myReverse(line.substr(start,i-start))+" "; else ans=myReverse(line.substr(start,i-start))+" "; start=i+1; i=start; } else i++; } ans+=myReverse(line.substr(start,line.size()-1))+" "; return ans; } string toReverseWord(string line){ string ans; //ans.resize(line.size()); //resize是使其重新分配 st end=line.size()-1; for(int i=line.size()-1;i>=0;){ //所示st则i必须大于0 cout<<i<<" "; if(line[i]==' '){ cout<<"space"<<" "; /*if(!ans.empty()) ans+=line.substr(i+1,end-i)+" "; else ans=line.substr(i+1,end-i)+" ";*/ ans+=line.substr(i+1,end-i)+" "; //和上面注释的一样 end=i-1; cout<<ans<<endl; } i--; } cout<<"right"<<endl; ans+=line.substr(0,end+1)+" "; return ans; } int main(void){ string line; //string l; //string deal; getline(cin,line); cout<<toReverseString(line)<<endl; cout<<toReverseWord(line)<<endl; system("pause"); return 0; }