将字符串进行反转
(以下代码均在VS2015测试通过)借用了网上的思路,给自己提醒
方法1:使用string.h中的strrev函数 将字符串数组反转
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char s[]= "Hello world";
_strrev(s);
cout << s;
return 0;
}
方法2:使用algorithm中的reverse方法。参数使用如下:
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
string s = "Hello world";
reverse(s.begin(), s.end());
cout << s << endl;
return 0;
}
方法3:自己编写函数 首尾互换元素,借助中间值 还是调换的字符串数组
#include<iostream>
using namespace std;
void reverse(char *s, int n)
{
for (int i = 0, j = n - 1; i < j; i++, j--)
{
char c = s[i];
s[i] = s[j];
s[j] = c;
}
}
int main()
{
char s[] = "Hello world";
reverse(s, 11);
cout << s << endl;
return 0;
}