【问题标题】:Java String Break by space after positionJava字符串在位置后按空格分隔
【发布时间】:2016-01-23 13:16:59
【问题描述】:

我有一个很长的字符串,想把它分解成多个子字符串,这样我就可以在菜单中将它显示为一个段落而不是一个长行。但我不想在一个单词中间把它打断(所以每隔 n 个字符打断一次是行不通的)。

所以我想通过在某个点之后第一次出现字符串中的任何字符来分解字符串(在我的情况下,字符将是空格和分号,但它们可以是任何东西) .

类似:

String result[] = breakString(baseString, // String
                              lineLength, // int
                              breakChars) // String

【问题讨论】:

标签: java string


【解决方案1】:

考虑先用中断字符分割,然后将分割产生的段的长度相加,直到达到你的行长度。

【讨论】:

    【解决方案2】:

    这是一种方法。我将“在某个点之后第一次出现字符串中的任何字符”表示在某个lineLength 之后的下一个breakChars 实例应该是一行的结尾。因此,breakString("aaabc", 2, "b") 将返回 {"aaab", "c"}

    static String[] breakString(String baseString, int lineLength, String breakChars) {
        // find `lineLength` or more characters of the String, until the `breakChars` string
        Pattern p = Pattern.compile(".{" + lineLength + ",}?" + Pattern.quote(breakChars));
    
        Matcher m = p.matcher(baseString);
        List<String> list = new LinkedList<>();
        int index = 0;
        while (m.find(index)) {
            String s = m.group();
            list.add(s);
    
            // find another match starting at the end of the last one
            index = m.end();
        }
    
        if (index < baseString.length() - 1) {
            list.add(baseString.substring(index));
        }
    
        return list.toArray(new String[list.size()]);
    }
    

    【讨论】:

      猜你喜欢
      • 2013-05-16
      • 2021-02-25
      • 1970-01-01
      • 2012-04-19
      • 1970-01-01
      • 2015-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多