import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class SentenceSplit {
/**
* show separate a English sentence into separate lines, each line has a same max length.
* Author: Roy He <br>
* Datetime:2009.07.08 <br>
* @param str String
* @param maxLengthOfLine int
* @param result List<String>
* @exception WordLengthException
* @return null
*/
public static void split(String str,int maxLengthOfLine,List<String> result) throws WordLengthException
{
//attention:if there are sequential break char(like ' ','.','?','!'),this program may not run correctly.
String [] lines = {"",""};
if(str.length() <= maxLengthOfLine)
{
result.add(str);
return;
}
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();
if(words[i].length()>maxLengthOfLine)throw new WordLengthException();
}
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 > maxLengthOfLine)
{
sperator = temp;
break;
}
}
System.out.println("sperator="+sperator);
if(sperator == 0 )
{
lines[1] = oldstr;
}else
{
if(sperator < oldstr.length() && sperator < maxLengthOfLine)sperator++;//如果还有空间,把空格放在行末.以后下行行首出现空格!
lines[0] = oldstr.substring(0,sperator);
lines[1] = oldstr.substring(sperator,str.length());
}
System.out.println("sperator="+sperator);
result.add(lines[0]);
if(lines[1].length() > maxLengthOfLine)
{
split(lines[1],maxLengthOfLine,result);//如果第二行还是太长,递归分解.
}else
result.add(lines[1]);
}
public static void main(String args[])
{
String str = "News and pictures from the world of celebrity, royalty, entertainment, film and music; fashion trends and videos; health and beauty; celebrity profiles;";
List<String> result = new ArrayList<String>();
try {
split(str,15,result);
} catch (WordLengthException e) {
e.printStackTrace();
}
System.out.println(result.size()+"lines!");
Iterator<String> it = result.iterator();
while(it.hasNext())
{
System.out.println("*******"+it.next());
}
}
}
class WordLengthException extends Exception
{
private static final String ERROR_MSG = "The max length of the line can not less than any word in the sentence.";
public WordLengthException()
{
super(ERROR_MSG);
}
}