public String chopString(String s) {
String tmp = "";
for (int i = 0; i < s.length() - 1; i++) {
if (tmp.length() % 30 == 0)
tmp += "<br>";
tmp += s.substring(i, i + 1);
}
return tmp;
}
Here is another implementation:
public class BreakString
{
/**
* break up a String into lines, and separate them with <br>,
* breaking into lineLength chunks, ignoring word boundaries.
* This code is optimised for speed by attempting to keep the inner
loop
* as tight as possible, at the expense of some extra setup work.
* @param s string to break
* @param lineLength length of desired lines (not counting the
<br>).
* @return string with <br> separators inserted.
*/
public static String breakString(String s, int lineLength)
{
final int stringLength = s.length();
if ( stringLength <= lineLength )
{
return s;
}
// count of one or more lines, including partial lines.
// Last line may be full or partial.
final int lines = (stringLength + lineLength - 1 ) / lineLength;
// compute space needed for original string
// plus a <br> on all but the last line.
final StringBuilder sb =
new StringBuilder(stringLength
+ ( "<br>\n".length()
* ( lines-1 ) ) );
// do all but the last line, possibly 0 lines.
final int startOfLastLine = (lines-1) * lineLength;
for ( int i=0; i < startOfLastLine; i+= lineLength )
{
// copy over one complete line.
sb.append( s.substring( i, i+lineLength ) );
sb.append( "<br>\n" );
}
// copy over the last line, full or partial without <br>
sb.append( s.substring( startOfLastLine, stringLength ) );
return sb.toString();
}
/**
* main, test driver
* @param args not used.
*/
public static void main ( String[] args )
{
System.out.println(breakString("123456789012345678901234567",
3));
System.out.println(breakString("123456789012345678901234567890",
30));
System.out.println(breakString("1234567890123456789012345678901", 30
));
System.out.println(breakString("123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123",
30) );
}
}
}