解法一:倒序输出
include <bits/stdc++.h>
using namespace std;
int main()
{
string s; //string类型的字符串并无‘\0’,
//一个没有‘\0’的字符数组
getline(cin,s); //字符串中有空格需要整行读入
int i;
for(i=(int)s.length()-1;i>=0;i--) //强制转换,s.length是一个unsigned的类型,-1会出错;
{ //长度为字符串的长度-1,因为是在数组里。
cout<<s[i];
}
return 0;
}
/*
length size 最好进行类型转换
*/
int i=(int)s.length()-1;
for(i;i>=0;i++)
{
}
解法二:reverse
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s;
getline(cin,s);
reverse(s.begin(),s.end()); //reverse函数
cout<<s<<endl;
reuturn 0 ;
}
解法三:
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s;
getline(cin,s);
for(i=0;i<s.length()/2;i++)
{
swap(s[i],s[length-1-i]); //对半交换元素
}
cout<<s<<endl;
return 0;
}
/*当数组长度为4的时候
其索引就是(0+3)/2=1.5,i=0,1
当数组长度为5的时候中间值为2,x=0,1均可以
中间值也就是所谓的
s.length()/2
此时
for(i=0;i<s.length()/2;i++)
{
swap(s[i],s[s.length()-1-i]);
}
cout<<s;
*/

被折叠的 条评论
为什么被折叠?



