Is there a function to reverse the order of a string?
Is there a function to reverse the order of a string?
strrev
"Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
-Christopher Hitchens
Thank you.
If you have strrev, otherwise you can write your own really easily. This one is independent of any header files, meaning you don't need string.h :-)
Or you can use strlen and get rid of the first explicit loop :-)Code:#include <stdio.h> static void revstr(char *s) { char *start; char *end; /* Find the end */ for (end = s; *end != '\0'; end++) { /* Do nothing */ } /* Reverse the string */ for (start = s, --end; start < end; start++, end--) { char temp = *start; *start = *end; *end = temp; } } int main(void) { char s[] = "A string"; revstr(s); printf("%s\n", s); return 0; }
Code:#include <string.h> static void revstr(char *s) { char *start; char *end; /* Find the end */ end = s + (strlen(s) - 1); /* Reverse the string */ for (start = s; start < end; start++, end--) { char temp = *start; *start = *end; *end = temp; } }
*Cela*
Thank you.
Here's another way of doing it:
Code:#include <stdio.h> void reverse(char *str) { int i,j=strlen(str)-1; for(i=0;i<j;++i,--j) str[i] ^= str[j] ^= str[i] ^= str[j]; } int main() { char *s = "This is a test string."; printf("%s\n", s); reverse(s); printf("%s\n", s); }
Code:/* #include <stdio.h> #include <string.h> */ void reverse(char *str) { /* strlen returns size_t but at times I use int */ int i,j=strlen(str)-1; for(i=0;i<j;++i,--j) /* http://www.eskimo.com/~scs/C-faq/q3.8.html */ str[i] ^= str[j] ^= str[i] ^= str[j]; } int main() { /* On some machines stores the string in read only memory */ char *s = "This is a test string."; printf("%s\n", s); reverse(s); printf("%s\n", s); /* main returns an integer value */ /* return 0; */ }