Insert line breaks into a long string to fit a length : Minimizing the risk of cutting a word unexpectedly


import java.util.Calendar;
import java.util.Date;
 
 
public class test {
  public static void main(String[] argv) {
	  String s = "Here, startIndex specifies the beginning index, and endIndex specifies the stopping point. The string returned contains all the characters from the beginning index, up to, but not including, the ending index. The following program uses substring( ) to replace all instances of one substring with another within a string:";// used to insert any string or character at the specified position in the given string."; 	  
      int charsPerLine = 10;
      System.out.println(insertLinebreaks(s, charsPerLine));	     
  }
  
  public static String insertLinebreaks(String s, int charsPerLine){	  
      String[] tokens = s.split(" ");
      String temp="";
      String retS = "";
      int maxRightPadding = 5; // Increasing the value'll minimize the risk of cutting a word unexpectedly, but woun't give good performance to break continuous string(without space/br). 
	  
      for (int i=0; i charsPerLine){
	      if((charsPerLine - temp.length()) <= maxRightPadding){
		  retS = retS+temp+ "\n";				  
		  for(int o=0; o<= (tokens[i].length()/charsPerLine); o++){
		      if(o< tokens[i].length()/charsPerLine){						  
			  retS = retS + tokens[i].substring((o*charsPerLine), ((o*charsPerLine) + charsPerLine))+"\n";
		      }
						  
		      if(o == tokens[i].length()/charsPerLine){						  
			  temp = tokens[i].substring(o*charsPerLine);							  						 				 
		      }						  
		  }
	     }else{
		  retS = retS+temp+ "\n";
		  temp = tokens[i];				  				 
	     }
	 }else{
	     if((temp.length() + tokens[i].length()) <= charsPerLine){				  
		 temp = temp+" "+tokens[i];				 
	     }
	     else{				 
		 retS = retS+ temp + "\n";				 
		 temp = tokens[i];
	     }
         }		  		 		  
     }
     retS = retS +temp+ "\n";
     return retS;	  
  }  
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s