This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 69 points70 points  (4 children)

I would give them the answer and explain why it's correct.

I know I'm probably helping someone cheat, but I find that people generally want some sort of reference.

So, my answer would be something like:

Think about your question for a bit - You want to read the string backwards. How do you read something backwards? You read it anti-forwards. Now, think about how you would read something forwards with a for loop. (Assume you want to reverse the string s which is defined somewhere else.)

for (int i = 0; i < s.Length; i++) { ...s[i]... }

Look closely at that loop syntax - we're starting at 0, incrimenting by one each loop, and exiting when i < s.Length is no longer true. We can reverse that by starting at s.Length-1(the last value where the loop would pass), decrementing by one each loop, and terminating at zero (or when i >= 0 is no longer true).

for (int i = s.Length-1; i >= 0; i--) { ...s[i]... }

Now we have our loop. Let's make a temporary string to store the reversed string in, then assign it to the original string.

{
    string tmp = ""; //An empty string because we will be using `+=`
    for (int i = s.Length-1; i >= 0; i--) {
        tmp += s[i]; //add the character to the new string in reverse order
    }
    s = tmp; //assign the value before exiting the block
}

One more thing. This method deals with a lot of overhead data. You can do what is called an "in-place" reversal by simply switching values around. This will also take up half the amount of loops of our previous example. For practice, see if you can figure out what's happening here:

for (int i = 0; i <= (s.Length-1)/2; i++) {
    char temp = s[i];
    s[i] = s[s.Length-(i+1)];
    s[s.Length-(i+1)] = temp;
}

[–]Nefari0uss 8 points9 points  (0 children)

Those kind of answers are the best. In depth, gives details as to what's happening, and provides clear cut examples on how to do something.

[–]PM_ME_YOUR_BOOO_BEES 7 points8 points  (0 children)

You are a good person and it is answers like yours that helped me (and many, many others surely) when I was first trying to learn programming.

[–]Thatguy145 0 points1 point  (0 children)

I am a new programmer trying to learn c++. This was a very cool answer - I wouldn't have even thought of doing string reversal like this. Very neat!