Sunday, August 12, 2012

Simple stuff in java that I learnt today

Coming from a C background I never really got to write code in java to do some string processing. The other day I was doing some simple stuff in java and I hit these problems.
  1. Converting a string to an integer array: It came as a shocker when I couldn't get this to work right away. However a quick google search gave me a whole bunch of answers. I have written the method below:
      public int[] getIntArrayFromString(String s) {
      int[] result = new int[s.length()];
      for(int i =0; i < s.length(); i++) 
        result[i] = Character.digit(s.charAt(i));
      return result;
    }
    
    The Character wrapper class comes to rescue here. However the logic for digit is pretty similar to C logic. Where the char ASCII vale is taken and subtracted from ASCII value of One '1'.
  2. Reversing a string:
    Again using String Buffer to do this is the best method possible.One from the front and the other from the rear.
     
      public static String revertString(String msg) {
          StringBuffer sb = new StringBuffer();
          for(int i=msg.length() - 1, i >= 0; i++ )
              sb.append(msg.charAt(i));
          return sb.toString();
      }
    
Super simple stuff wanted to see if my coding tags work.

No comments:

Post a Comment