C Language Implementation String reverse

Source: Internet
Author: User
Tags printf strlen

Interview often encounter problems, C language implementation string reverse. such as input "ABCD", Output "DCBA".

Recently tidied up, the following code has been tested.

#define Max 200
main()
{
   char str[Max];
   printf("请输入字符串:");
   gets(str);
   int len=0;
   char *strlen=str;
   char *left=str;
   char temp;
   while(*strlen++)len++;
   strlen-=2;//这里很值得思考
   while(left<strlen)
   {
      temp=*left;
      *left++=*strlen;
      *strlen--=temp;
   }
   printf("逆序后的字符串为:");
   int i;
   for(i=0;i<len;i++)
       printf("%c",str[i]);
   printf("\n");
   system("pause");
}

The following is the code given by Ms C Library:

1.char * __cdecl strrev (char * string)
0.9
3. char *start = string;
4. char *left = string;
5. Char ch;
6. While (*string++)/* Find end of String * *
7. ;
8. string = 2;
9. While (left < string)
Ten. {
ch = *left;
*left++ = *string;
*string--= ch;
. }
Return (start);
16.}

Ms Given the code is relatively concise, write better than my!

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.