JAVA中如何将一句英文分成几行,断行不断单词

用Java语言编写一个方法,接受的输入为一个字符串和一个数字(最大长度)。这个函数会返回一个新的字符串,内容和输入的字符串一样,但是会在适当的地方加上一些换行符(\n),使得每一行的长度都不能超过输入的数字。换行符应该尽量位于单词之间,不要将完整的单词断开。

例如输入字符串为:

The function returns the string, but with line breaks inserted atjust the right places to make sure that no line is longer than the columnnumber.

最大长度为60,得到的结果应该是:

The function returns the string, but with line breaks\n
inserted at just the right places to make sure that no line\n
is longer than the column number.

代码如下

package com.example.LineFeed;

public class LineFeed {
    public String makelinefeed(String s) {
        //用空格作为分隔符,将单词存到字符数组里面
        String[] str = s.split(" ");
        //利用StringBuffer对字符串进行修改
        StringBuffer buffer = new StringBuffer();
        //判断单词长度,计算
        int len = 0;
        for (int i = 0; i < str.length; i++) {
            //System.out.println(str);
            //len = str[i].length();
            //叠加
            len += str[i].length();
            //System.out.println(len);
            if (len > 60) {
                buffer.append("\n" + str[i] + " ");//利用StringBuffer对字符串进行修改
                len = str[i].length()+1;//+1为换行后读出空格一位
            //System.out.println(len);
            } else {
                buffer.append(str[i] + " ");
                len++;
            //System.out.println(len);
            }
        }
        return buffer.toString();
    }

    public static void main(String[] args) {
        LineFeed lf = new LineFeed();
        System.out
                .println(lf
                        .makelinefeed("The function returns the string, but with line breaks inserted at just the right places to make sure that no line is longer than the column number."));
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值