方法一:
1、 用一个字符数组调用cin.getline()接收字符串;
2、 用循环把字符数组里面的字符前后交换
3、 代码:
#include
#include
#include
using namespace std;
int main()
{
char a[50];
memset(a,0,sizeof(a));
int i=0,j;
char t;
cin.getline(a,50,'\n');
for(i=0,j=strlen(a)-1;i
{
t=a;
a=a[j];
a[j]=t;
}
cout<
cin.get();
return 0;
}
4、该方法的缺点:字符数组大小是固定的,如果输入字符串长度超过字符数组的大小,将只能处理字符数组大小长度的子字符串。
方法二:
1、 用string型变量接收一个字符串;
2、 用循环把字符串中的字符位置前后倒置;
3、 代码:
#include
#include
#include
using namespace std;
int main()
{
string str;
getline(cin,str);
for(int i=0,j=str.size()-1;i
{
char t = str;
str = str[j];
str[j] = t;
}
cout<
cin.get();
return 0;
}
4、 优缺点:能够接收不知道长度的字符串,但是调用了string,程序会稍大。
方法三:
1、 用string型变量接收一个字符串;
2、 调用STL的reverse(first,last)来反转字符串;
3、 代码:
#include
#include
#include
using namespace std;
int main()
{
string str;
getline(cin,str);
reverse(str.begin(),str.end());
cout<
cin.get();
return 0;
}
4、优缺点:该方法的效率高,代码简洁,但是程序可能会稍大。
[ Last edited by bslt on 2009-5-18 at 16:17 ] |