[C Language] Reverse string order

Source: Internet
Author: User

[C Language] Reverse string order

There are multiple methods to reverse string order. The following methods are used to convert strings: // non-recursive string inversion: char * reverse (char * str) {if (! Str) {return NULL;} int len = strlen (str); int I, j; char temp; for (I = 0, j = len-1; I <j; I ++, j --) {// character temp = str [I]; str [I] = str [j]; str [j] = temp;} return str;} int main () {char src [] = {"abcdef"}; char * pdest = reverse (src ); puts (src); return 0;} // recursion is a stack structure: # include <stdio. h> # include <assert. h> void reverse_string (const char * const string) {assert (string); if (* string = '\ 0') return; Else reverse_string (string + 1); // first press the character stack putchar (* string); // then output the characters in the first and second order} int main () {char string [20] = {0}; scanf ("% [^ \ n]", string); reverse_string (string); printf ("\ n "); return 0;}: (if other library functions are not required) # include <stdio. h> # include <assert. h> int my_strlen (const char * string) {assert (string); if (* string = '\ 0') {return ;} else return 1 + my_strlen (string + 1);} char * reverse_string (char * string, int len) {Assert (string); if (! String) {return NULL;} if (len> 1) {char tmp = string [0]; string [0] = string [len-1]; string [len-1] = '\ 0'; // The last character will not process reverse_string (string + 1, len-2) at next recursion; // recursive call, every call, reduce a string [len-1] = tmp;} return string;} int main () {char string [20] = {0 }; int len; scanf ("% s", string); len = my_strlen (string); reverse_string (string, len); printf ("% s \ n", string ); return 0 ;}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.