简体   繁体   中英

Understanding a C++ function for reversing a string using ^=

The code below returns a reversed string. For example, it take input " codebyte " and returns " etybedoc ".

string FirstReverse(string str) {
    for(int i = 0, j = str.length() - 1; i < str.length() / 2; i++, j--)
    {
        str[i]^=str[j]^=str[i]^=str[j];
    }
    return str;
}

I am lost as to how this function works:

  1. Why is the ^= -operator being used? It is a bitwise operator but why is it being used here?
  2. Why is str.length() divided by 2 in the for loop?
  3. What is with the alteration of str[i] and str[j] ?

I want to work though it with values but I don't know where to begin. The introductory textbook I used did not cover this.

As an answer:

  • It's a swapping functionality similar to the famous bit-twiddling hacks.
    • A detailed explanation of this swapping mechanism can be found here .
  • The length is divided by two because otherwise you would undo every swap and end up with the original string again.
  • The indices i and j run against each other (from the beginning or end, respectively).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM