public class SentenceSplit {
public static String[] split(String str,int firstLineMaxLength)
{
//attention:if there are sequential break char(like ' ','.','?','!'),this program may not run correctly.
String [] lines = {"",""};
if(str.length() <= firstLineMaxLength)
{
lines[0] = str;
return lines;
}
String oldstr = str;
System.out.println(str.length());
// str = str.replace(".", " ");
// str = str.replace("?", " ");
// str = str.replace("!", " ");
String [] words = str.split(" ");
int total = 0;
for(int i=0;i<words.length;i++)
{
System.out.print(words[i]+"("+words[i].length()+")");
total += words[i].length();
}
System.out.println("total="+total);
int sperator=0;
int temp=0;
for(int i=0;i<words.length;i++)
{
temp = sperator;
if(i>0)sperator++;
sperator += words[i].length();
if(sperator > firstLineMaxLength)
{
sperator = temp;
break;
}
}
System.out.println("sperator="+sperator);
if(sperator == 0 )
{
lines[1] = oldstr;
}else
{
if(sperator < oldstr.length() && sperator < firstLineMaxLength)sperator++;
lines[0] = oldstr.substring(0,sperator);
lines[1] = oldstr.substring(sperator,str.length());
}
System.out.println("sperator="+sperator);
// if(lines[1].length() > firstLineMaxLength)
// {
// String lines2[] = split(lines[1],firstLineMaxLength);
// for(int i=0;i<lines2.length;i++)
// System.out.println("line"+i+":"+lines2[i]);
// }想用递归实现分成多行,还没有实现
return lines;
}
public static void main(String args[])
{
String str = "Have you ever wondered how a website removed the underline that usually acco?";
String lines[] = split(str,31);
System.out.println(lines.length+"lines!");
for(int i=0;i<lines.length;i++)
System.out.println("line"+i+":"+lines[i]);
}
}