习题5.16 输入一个字符串,把其中的字符按逆序输出。如输入LIGHT,输出THGIL。
(1) 用字符数组方法
代码:
#include<iostream>
using namespace std;
int main()
{
int i,j;
char arr[100],temp;
cout << "请输入字符串:" << endl;
cin >> arr;
for (i = 0; arr[i] != '\0'; ++i);
for (j = 0;j <= ((i -1) / 2); ++j) //逆序
{
temp = arr[j];
arr[j] = arr[i - j - 1];
arr[i - j - 1] = temp;
}
cout << "逆序后为:" << arr << endl;
return 0;
}
(2) 用string 方法
代码:
#include<iostream>
using namespace std;
int main()
{
int i;
string str;
char temp;
cout << "请输入字符串:" << endl;
cin >> str;
for (i = 0;i <= (str.length() - 1) / 2; ++i) //逆序
{
temp = str[i];
str[i] = str[str.length() - i - 1];
str[str.length() - i - 1] = temp;
}
cout << "逆序后为:" << str << endl;
return 0;
}