To reverse a string

Source: Internet
Author: User

There are multiple ways to implement a string in reverse order, and the following three methods are all manipulated on the original string.

Way one. Operations using arrays

1 Char*REVERSESTR (Char*str)2 {3     Char*temp =str;4     intIndexleft =0;5     intIndexright =0;6     if(str = =NULL)7     {8         returnNULL;9     }Ten      while(*temp! =' /') One     { Aindexright++; -temp++; -     } the     //point to the last character ' \ s ' of the previous -Indexright = Indexright-1; -      -      while(Indexright >indexleft) +     { -         Chartemp =Str[indexleft]; +str[indexleft++] =Str[indexright]; Astr[indexright--] =temp; at     } -  -     returnstr; -      -}


Way two. Manipulate with pointers

Char*REVERSESTR (Char*str) {    Char*left =str; Char*right =str; if(str = =NULL) {        returnNULL; }     while(*right! =' /') { Right++; } Right--;  while(Right >Left ) {        Chartemp = *Right ; *right++ = *Left ; *left++ =temp; }    returnstr;}

Mode three. Do not use the third variable

1 Char*REVERSESTR1 (Char*str)2 {3     Char*left =str;4     Char*right =str;5     if(str = =NULL)6     {7         returnNULL;8     }9      while(*right! =' /')Ten     { Oneright++; A     } -right--; -     /*characteristics of using XOR operation a = a^b^b B = A^b^a*/ the      while(Right >Left ) -     { -*left = *left ^ *Right ; -*right = *left ^ *Right ; +*left = *left ^ *Right ; -left++; +right--; A     } at     returnstr; -}

To reverse a string

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.