第一种:使用algorithm中的reverse函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #include <iostream> #include <string> #include <algorithm> using namespace std; int main() { string s = "hello" ; reverse(s.begin(),s.end()); cout<<s<<endl; return 0; } |
第二种:自己编写
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #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; } |
第三种:使用string.h中的strrev函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #include <iostream> #include <cstring> using namespace std; int main() { char s[]= "hello" ; strrev(s); cout<<s<<endl; return 0; } |