Reverse a string (the library function cannot be used with a recursive implementation)

Source: Internet
Author: User

Reverse the two strings to set two pointers, one to the beginning of the string, and one to the address of the element at the end of the string (the address of the element in front of the "Start<end") end, as long as the two addresses point to the element to exchange.

The implementation code is as follows:

#include <stdio.h>
#include <string.h>
void reverse (char *str)
{
char tmp = 0;
Char *start;
Char *end;
start = str;
end = str + strlen (str)-1;
while (Start < end)
{
TMP = *start;
*start = *end;
*end = tmp;
Start + +;
End--;

}
}
int main ()
{
Char str[] = "abcdef";
Reverse (str);

printf ("%s", str);
return 0;
}
It can also be implemented using recursive methods:

First the first element of the string "ABCdef" is saved, and then the last element is placed in the position of the first element, the last element is assigned a value of "\", when the function is called the first address of the string is passed back to the address of an element, to determine whether its length is greater than 1, If greater than one is repeated above, the function returns the last function returned after the function has been recursively completed, assigning the value of the last function saved to the position of the len-1 in the function.

The code is implemented as follows:

#include <stdio.h>
#include <assert.h>
int Str_len (char *str)//Simulation implementation strlen function
{
ASSERT (str);
int count = 0;
while (*STR)
{
count++;
str++;
}

return count;
}
void reverse (char *str)//String reverse function
{
char *p = str;
char tmp = 0;
int len = 0;
len = Str_len (p);
if (Len > 1)
{
TMP = p[0];
P[0] = p[len-1];
P[len-1] = ' + ';
Reverse (p + 1);
P[LEN-1] = tmp;
}
}
int main ()
{
Char str[] = "abcdef";
Reverse (str);
printf ("%s\n", str);
System ("pause");
return 0;
}

Reverse a string (the library function cannot be used with a recursive implementation)

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.