Java如何在一定数量的字符后在空格处拆分字符串

JFr*_*man -1 java string split

(问题已关闭,因为范围很广,所以我试图更清楚)

我发现了很多重复的问题,但它们都是其他编程语言。

我有一个字符串,每 68 个字符我想打破这个字符串。但这很可能会导致句子在单词中间被打断。

例如

我喜欢猫和狗,但不喜欢它们携带的逃跑。此外,我认为猫有时很粗鲁,因为当我需要它们时它们也不拥抱我。总的来说,猫和狗都很棒。

相反,我想字符 68之前最近的空格处断开这些字符串。然后我可以以不中断中间单词的方式呈现字符串。

最终,这个问题可能可以通过 for 循环一次检查每个字符 68 及以下字符以查看它们是否为空格来解决。当它找到空间时,它可以在那个字符处被切割。或者,我可以一次添加一个单词,直到我通过 68 个字符而不添加最后一个单词。第三种选择是在第 68 个字符处对字符串进行子字符串化,然后在空格字符的 lastIndexOf 处再次对字符串进行子字符串化。

然而,我所有的想法似乎都非常低效,我想知道是否有任何已经创建或内置的字符串方法可以做到这一点?

Ram*_*asi 6

您可以使用WordUtils.wrap()Apache commons [code] 中的方法

代码:

import org.apache.commons.lang3.*;

class WrapTest {
    public static void main (String[] args)  {
        String str = "I am a love cats and dogs but not the flees they carry. Also i think that cats are sometimes rude because they do not hug me when i want them too. Overall though cats and dogs are both great.";
        str = WordUtils.wrap(str, 68);
        System.out.println(str);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

I am a love cats and dogs but not the flees they carry. Also i think
that cats are sometimes rude because they do not hug me when i want
them too. Overall though cats and dogs are both great.
Run Code Online (Sandbox Code Playgroud)