Use C language recursion and non-recursion to implement the string inversion function char * reverse (char * str)

Source: Internet
Author: User

The Code is as follows:

Copy codeThe Code is as follows: // Recursive string Inversion
Char * reverse (char * str)
{
If (! Str)
{
Return NULL;
}

Int len = strlen (str );
If (len> 1)
{
Char ctemp = str [0];
Str [0] = str [len-1];
Str [len-1] = '/0'; // The last character will not be processed at next Recursion
Reverse (str + 1); // recursive call
Str [len-1] = ctemp;
}

Return str;
}

// Non-recursive string Inversion
Char * reverse (char * str)
{
If (! Str)
{
Return NULL;
}

Int len = strlen (str );
Char temp;
For (int I = 0; I <len/2; I ++)
{
// Exchange the characters at the first and second locations
Temp = * (str + I );
* (Str + I) = * (str + len-1-I );
* (Str + len-1-I) = temp;
}

Return str;
}
Int _ tmain (int argc, _ TCHAR * argv [])
{
Char src [] = {"abcdef "};
Char * pdest = reverse (src );
Getchar ();
Return 0;
}

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.