第一种:使用string.h中的strrev函数
- #include <iostream>
- #include <cstring>
- using namespace std;
-
- int main()
- {
- char s[]="hello";
-
- strrev(s);
-
- cout<<s<<endl;
-
- return 0;
- }
第二种:使用algorithm中的reverse函数
- #include <iostream>
- #include <string>
- #include <algorithm>
- using namespace std;
-
- int main()
- {
- string s = "hello";
-
- reverse(s.begin(),s.end());
-
- cout<<s<<endl;
-
- return 0;
- }
第三种:自己编写
- #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";
-
- Reverse(s,5);
-
- cout<<s<<endl;
-
- return 0;
- }
第四种: - #include <iostream>
- using namespace std;
-
- string resverstr(const string str)
- {
- string temp;
- int len = str.length();
- cout << "字符串长度"<<len << endl;
- for (int i = 0; i < len; i++)
- {
- temp = str[i] + temp;
- }
- return temp;
- }
第五种: -
- string resverstr5(string str)
- {
- int len = str.length();
- cout << "字符串长度" << len << endl;
- for (int i = 0; i < len/2; i++)
- {
- char c = str[i];
- str[i] = str[str.length() - i - 1];
- str[str.length() - i - 1] = c;
- }
- return str;
- }
|