Method of implementing string inversion function char *reverse (char *str) using recursive and non-recursive C language _c language

Source: Internet
Author: User

The code looks like this:

Copy Code code as follows:

//recursive implementation 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 the next time it is recursive
Reverse (str+1); Recursive call
Str[len-1] = ctemp;
}

return str;
}

//non-recursive implementation of 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 two characters before and after the corresponding positions
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.