r/programmingchallenges • • May 19 '11

Challenge: Reverse a string in place

This simple challenge is a frequent interview question. Write a program that reverses a string in place. "In place" means no declaring a second string or other buffer-- you get only one string variable to work with.

Input:

 "Test string."

Output:

".gnirts tseT"

edit: obviously, this is only feasible in a language with mutable strings.

22 Upvotes

65 comments sorted by

View all comments

Show parent comment

4

u/[deleted] Sep 07 '11 edited Sep 07 '11

The problem of course being that you could just do:

  class Main
  {
       public static void main (String[] args)
       {
          StringBuilder sb = new StringBuilder("abcdefg");
          sb = sb.reverse();
          System.out.println(sb);
       }
  }

This is actually one of the reasons I'm addicted to Java. All the code is written for me. That sounds kinda lame in a way but between the awesome documentation and no need to write remedial code it's a god send.

I think this is a fun beginners exercise but once it's mastered, I think it's important to learn that at least in Java, it's good to know when code is already written for you and when you need to write it yourself.