|
Re: Splitting a String to a specific length
|
Posted: Jan 7, 2003 11:54 AM
|
|
Here is the code. Use breakString () method . Thanks Kishori ************** Code starts here *************************
public class StringBreaker {
public static void main ( String[] args ) {
StringBreaker strb = new StringBreaker ( ) ;
String str = "Can someone please help me with this problem";
System.out.println ( str ) ;
str = strb.breakString ( str, 10 ) ;
System.out.println ( str ) ;
}
public String breakString ( String str , int perLine ) {
if ( perLine <= 0 ) {
// You may want to throw exception here.
//I am just returning original string
return str;
}
if ( str == null ) {
return str;
}
// Convert the string into stringbuffer for efficient string manipulation
StringBuffer sb = new StringBuffer ( str ) ;
// Get the length of origianl string
int len = sb.length() ;
if ( len < perLine ) {
return str;
}
/* Now we need to insert a new line character at every perLine */
// Get the newline character for the specific platform
String newLine = System.getProperty ( "line.separator" ) ;
// New line is not always one character. It depends on platform
int newLineLength = newLine.length() ;
// Let us compute the total number of new lines to be added
// Note that it will also add new line if total string length
// happens to be multiple of perLine. If you don't want it then do a check here
int totalNewLines = len / perLine ;
// Compute the length of final string
int finalLength = len + totalNewLines * newLineLength ;
for ( int i = perLine ; i < finalLength; i = i + perLine + newLineLength ) {
// Insert the new line chanrater in string now
sb.insert ( i, newLine ) ;
}
// We are done. Return the string object out of string buffer object
return sb.toString() ;
}
}
|
|