一个指定的时间间隔前一个字符字符串分割为一个字符串数组 [英] Splitting a string into a string array at a character before a specified interval

查看:129
本文介绍了一个指定的时间间隔前一个字符字符串分割为一个字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在找一个字符串分割成String数组在一个区间,但我不想一半被削减的话。例如:

I'm looking to split a string into a String array over an interval, but I don't want the words to be cut in half. For Example:

说出文字是:

Lorem Ipsum Sub Rosa Dolores Clairborne. The quick brown fox zipped quickly to the tall yellow fence and hopped to the other side.
Interval: 50

将被分为以下

separated[0]: "Lorem Ipsum Sub Rosa Dolores Clairborne. The quick brown"
separated[1]: "fox zipped quickly to the tall yellow fence and"
separated[2]: "hopped to the other side."

我一直试图弄清楚这一点,我想出最好的是:

I've been trying to figure this out, the best I've come up with is:

    private static String[] splitMessage(String text, int interval) {
    char[] splitText = text.toCharArray();
    String[] message = new String[(int) Math.ceil(((text.length() / (double)interval)))];
    int indexOfSpace = 0, previousIndex = 0, messageCursor = 0, pos = 0;
    for (int i = 0; i < splitText.length-1; i++) {
        if (splitText[i] == ' ') {
            indexOfSpace = i;
        } 
        if (pos == interval) {
            message[messageCursor] = text.substring(previousIndex, indexOfSpace);
            previousIndex = indexOfSpace;
            messageCursor++;
        }
        pos++;
    }
    return message;
}

这最终只能分裂的Lorem到第一个索引。有什么建议?

This ends up only splitting Lorem into the first index. Any suggestions?

推荐答案

我会建议使用 WordUtils的包裹功能来添加换行符在适当的包装点,然后 String.split(\\\\ \\\\ - [R N'); 来生成的字符串分割成字符串数组。

I would recommend using the WordUtils's Wrap function to add line breaks at the appropriate wrapping points, and then String.split("\\r?\\n"); to split the resulting string into an array of strings.

这篇关于一个指定的时间间隔前一个字符字符串分割为一个字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆