1. Using the Strrev function in String.h
#include <iostream> #include <cstring> using namespace std; int main () { char s[]= "Hello"; Strrev (s); cout<<s<<endl; return 0; }
2. Using the reverse function in algorithm
#include <iostream> #include <string> #include <algorithm> using namespace std; int main () { string s = "Hello"; Reverse (S.begin (), S.end ()); cout<<s<<endl; return 0; }
3. Write your own
#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; }
Or
Char *revstr (char *str, size_t len) { char *start = str; char *end = str + len-1; char ch; if (str = NULL) { while (Start < end) { ch = *start; *start++ = *end; *end--= ch; } } return str;}
The so-called string in C is simply an array of characters, followed by an 0x00 character to identify the end, so it's easy to reverse, as long as a loop turns the first character and the last character exchange, the second character and the penultimate character exchange ... If there are two characters in the middle (that is, an even number of strings that need to be reversed), swap if there is a character in the middle (that is, the string that needs to be reversed is an odd length), then you do not need to touch it. There is the last 0x00 character to identify the end of the string without moving it.
C language Reversal string