//关注备注部分知识点。 #include <iostream> #include <string><span style="white-space:pre"> </span><span style="color:#cc0000;">//1---需要了解cstring和string之间的区别</span> int main() { using namespace std; cout<<"Please Enter a string:\n"; string word; cin>>word;// // char temp;<span style="white-space:pre"> </span><span style="color:#cc0000;">//3---</span> int i,j; //<span style="white-space:pre"> </span>for(i=0,j=word.size()-1;i<=j;++i,--j) <span style="white-space:pre"> </span>for(i=0,j=word.length()-1;i<=j;++i,--j) <span style="color:#ff0000;">//2---word.size() word应该是个数组. <span style="font-family: Arial, Helvetica, sans-serif;">word.length()和</span><span style="font-family: Arial, Helvetica, sans-serif;"> word.size() 则表示数组的长度. 因为数组下标是从0开始的.所以 要-1 防止下标越界</span></span> { char temp;//内部声明temp在每次循环存在被分配和释放,相对for循环体前声明运行慢,循环结束即会释放 // char temp=word[i];<span style="font-family: Arial, Helvetica, sans-serif;"> </span><span style="font-family: Arial, Helvetica, sans-serif;"><span style="color:#ff0000;">//3--</span>-</span> // char temp=word[i];<span style="font-family: Arial, Helvetica, sans-serif;"> </span><span style="font-family: Arial, Helvetica, sans-serif;"><span style="color:#ff0000;">//3---</span></span> temp=word[i]; word[i]=word[j]; word[j]=temp; } cout<<word<<endl; return 0; }
时间: 2024-12-28 01:44:36