Thursday 30 July 2015

Java program to break the string after certain length

Java Program to break the String after certain length

Sometimes you want to break the long string value into smaller segments to display in small sized window.
For ex: In my case I had to display legend in Jasper Graph and my legend was quite long as compared to my Graph size So legend was not getting displayed properly.So I had to break the legend into equal sized smaller chunks .

Here is the sample program:


 /**  
  *   
  */  
 /**  
  * @author Dixit  
  *   
  */  
 public class BreakLongString {  
      public static void main(String a[]) {  
           String dn = "aaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbcccccccccccccdddddddddddeeeeeee";  
           StringBuffer legend = new StringBuffer();  
           if (dn.length() >= 20) {  
                String[] lines = Split(dn, 20, dn.length());  
                for (int j = 0; j < lines.length; j++) {  
                     legend.append(lines[j]);  
                     if (j != lines.length - 1) {  
                          legend.append("\n");  
                     }  
                }  
           }  
           System.out.println("legend:\n"+legend);  
      }  
      private static String[] Split(String text, int chunkSize, int maxLength) {  
           char[] data = text.toCharArray();  
           int len = Math.min(data.length, maxLength);  
           String[] result = new String[(len + chunkSize - 1) / chunkSize];  
           int linha = 0;  
           for (int i = 0; i < len; i += chunkSize) {  
                result[linha] = new String(data, i, Math.min(chunkSize, len - i));  
                linha++;  
           }  
           return result;  
      }  
 }  

No comments:

Post a Comment