Break a long string into lines with proper word wrapping

拟墨画扇 提交于 2019-12-10 18:08:21

问题


 String original = "This is a sentence.Rajesh want to test the application for the word split.";
 List matchList = new ArrayList();
 Pattern regex = Pattern.compile(".{1,10}(?:\\s|$)", Pattern.DOTALL);
 Matcher regexMatcher = regex.matcher(original);
 while (regexMatcher.find()) {
     matchList.add(regexMatcher.group());
 }
 System.out.println("Match List "+matchList);

I need to parse text into an array of lines that do not exceed 10 characters in length and should not have a break in word at the end of the line.

I used below logic in my scenario but the problem it is parsing to the nearest white space after 10 characters if there is a break at end of line

for eg: The actual sentence is "This is a sentence.Rajesh want to test the application for the word split." But after logic execution its getting as below.

Match List [This is a , nce.Rajesh , want to , test the , pplication , for the , word , split.]


回答1:


OK, so I've managed to get the following working, with max line length of 10, but also splitting the words that are longer than 10 correctly!

String original = "This is a sentence. Rajesh want to test the applications for the word split handling.";
List matchList = new ArrayList();
Pattern regex = Pattern.compile("(.{1,10}(?:\\s|$))|(.{0,10})", Pattern.DOTALL);
Matcher regexMatcher = regex.matcher(original);
while (regexMatcher.find()) {
  matchList.add(regexMatcher.group());
}
System.out.println("Match List "+matchList);

This is the result:

This is a 
sentence. 
Rajesh want 
to test 
the 
applicatio
ns word 
split 
handling.



回答2:


This question was tagged as Groovy at some point. Assuming a Groovy answer is still valid and you are not worried about preserving multiple white spaces (e.g. ' '):

def splitIntoLines(text, maxLineSize) {
    def words = text.split(/\s+/)
    def lines = ['']
    words.each { word ->
        def lastLine = (lines[-1] + ' ' + word).trim()
        if (lastLine.size() <= maxLineSize)
            // Change last line.
            lines[-1] = lastLine
        else
            // Add word as new line.
            lines << word
    }
    lines
}

// Tests...
def original = "This is a sentence. Rajesh want to test the application for the word split."

assert splitIntoLines(original, 10) == [
    "This is a",
    "sentence.",
    "Rajesh",
    "want to",
    "test the",
    "application",
    "for the",
    "word",
    "split."
]
assert splitIntoLines(original, 20) == [
    "This is a sentence.",
    "Rajesh want to test",
    "the application for",
    "the word split."
]
assert splitIntoLines(original, original.size()) == [original]



回答3:


I avoided regex as is doesn't pull the weight. This code word-wraps, and if a single word is more than 10 chars, breaks it. It also takes care of excess whitespace.

import static java.lang.Character.isWhitespace;

public static void main(String[] args) {
  final String original =
    "This is a sentence.Rajesh want to test the application for the word split.";
  final StringBuilder b = new StringBuilder(original.trim());
  final List<String> matchList = new ArrayList<String>();
  while (true) {
    b.delete(0, indexOfFirstNonWsChar(b));
    if (b.length() == 0) break;
    final int splitAt = lastIndexOfWsBeforeIndex(b, 10);
    matchList.add(b.substring(0, splitAt).trim());
    b.delete(0, splitAt);
  }
  System.out.println("Match List "+matchList);
}
static int lastIndexOfWsBeforeIndex(CharSequence s, int i) {
  if (s.length() <= i) return s.length();
  for (int j = i; j > 0; j--) if (isWhitespace(s.charAt(j-1))) return j;
  return i;
}
static int indexOfFirstNonWsChar(CharSequence s) {
  for (int i = 0; i < s.length(); i++) if (!isWhitespace(s.charAt(i))) return i;
  return s.length();
}

Prints:

Match List [This is a, sentence.R, ajesh, want to, test the, applicatio, n for the, word, split.]


来源:https://stackoverflow.com/questions/10702367/break-a-long-string-into-lines-with-proper-word-wrapping

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!