将一个英文句子分成两行


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]);
           
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值