VickTree
VickTree

Reputation: 909

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.

Upvotes: 2

Views: 218

Answers (1)

Thomas Lang
Thomas Lang

Reputation: 780

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).

Upvotes: 3

Related Questions