Monday, February 15, 2010

String with White Spaces in Java

 Hi,
In Most of the Data Formatting/Reports Applications we may require to create Strings with White Spaces with different sizes. I have found an issue on this as follows.

  1. Once i need to create spaces in between some data in my report, The implementation as 
  2. 1. StringBuffer  sb=new StringBuffer();
      2. sb.add("                                                     ");
      3. sb.add("Name :"+name);
      4. sb.add("               ");
      5. sb.add("age :"+age);
    
  3. Here the existing issue in line no 2 & 4, we have the string of Space Separator, But the code looks odd, and in case some added a space more in the same string it will be difficult to identify while Commiting the file in SVN or VSS .
  4. I made some implementation in Java Using Character Arrays which will give provide performance by using StringBuffer.
import java.util.Arrays;

   public class WhiteSpaceString {
       public final static char SPACE_SEPARATOR = 32;

       public static void main(String[] args) {
          System.out.println("|" + getWhitespaceString(10) + "|");
       }

       private static String getWhitespaceString(int length) {
          StringBuffer sb = new StringBuffer();
          char[] whiteSpace = new char[length];
          Arrays.fill(whiteSpace, SPACE_SEPARATOR);
          sb.append(whiteSpace);
          return sb.toString();
      }
   }

If you have any Better approach for the same please update me.
askeralim@gmail.com

No comments: