I have one big line with a large number of sentences with different number of words. I need to break this line into lines of at least 60 characters, but so that it can be broken down only by spaces. I know that in Guava there is a class Splitter. But if I use Splitter.fixedLength (60), then the string will be spelled. If you use Splitter.on (""), then each word will be highlighted in a separate line. What is the best way to do this?

    1 answer 1

    Try this:

    private String justify(String s, int limit) { StringBuilder justifiedText = new StringBuilder(); StringBuilder justifiedLine = new StringBuilder(); String[] words = s.split(" "); for (int i = 0; i < words.length; i++) { justifiedLine.append(words[i]).append(" "); if (i+1 == words.length || justifiedLine.length() + words[i+1].length() > limit) { justifiedLine.deleteCharAt(justifiedLine.length() - 1); justifiedText.append(justifiedLine.toString()).append(System.lineSeparator()); justifiedLine = new StringBuilder(); } } return justifiedText.toString(); }