Tuesday 6 May 2014

Project 1 - Reversing a string

We start of with an easy one, reversing a string. Even to a newbie programmer this shouldn't seem such a daunting task, but I'll still go through my thought process.

Obviously, nowadays reversing a string is as simple as calling a reverse() method and you're done. But where's the fun in that?

So, what I'll need is some way to extract single characters from a string. Luckily Java provides us with a charAt(int idx) method that returns a character at the specified index. Then I need a way to go through a whole string, and that's why God invented a for loop. Now I automatically started writing for(int i = 0; i < ...), but I saw that isn't going to work. I need to start at the end of the string, so I can append these characters to an empty string. For a beginner it's important to visualize this, so a piece of paper and a pencil is the greatest gift you can give yourself when starting to learn programming. Now we can rewrite the for loop and set the starting index on the strings length, but we must be careful. If we forget to subtract 1 from the length we get the glorious ArrayIndexOutOfBoundsException. Continuing with our for loop, we set the condition so that the loop goes on until its bigger or equal to 0. If we removed the 'equal to' part we can't append the last character. And the counter is set to i--, because we're descending down the string. Figuring this for loop was the meats of this project.

Now, String '+' vs. StringBuilder append()

This doesn't impact the solution of the project that much, but I figured it's still worth a mention. You can concatenate a String in two ways:

  • using built in '+' operator like this: string = string + newString;
  •  or using StringBuilder class: string.append(newString); 
In the end, both achieve the same result. Then why even bother choosing, you might ask? Everything has it's pros and cons, and so do these two methods. Using the StringBuilder is faster when you're appending to a string in a loop, because compilers aren't very good at concatenating strings in a loop, and they don't optimize the process very well. StringBuilder class is used where efficiency is needed, but we must be careful that we don't reduce the readability of the code.

String vs StringBuilder debate

Now we just slap a nice static method around our for loop, with a single String argument, and we're done. My code solution is not the only one possible, and probably not the best, so please feel free to leave comments if you have any comments or suggestions.

2 comments:

  1. Don't forget to overlook easy solutions as well :)
    new StringBuilder(str).reverse();

    ReplyDelete
    Replies
    1. I totally had that in mind. and I was going to mention it, but I somehow forgot.. Thanks for reminding me :)

      Delete