1 package no.sintef.util;
2
3 import java.util.regex.Matcher;
4 import java.util.regex.Pattern;
5
6 public class StringUtils {
7
8 private static final Pattern LINE_BREAK_PATTERN = Pattern.compile("//s+|//s*<br>//s*", Pattern.CASE_INSENSITIVE);
9 private static final String BR = "<br>";
10
11 public static String addLinebreaks(String s, final int maxLineLength) {
12 Matcher m = LINE_BREAK_PATTERN.matcher(s);
13 StringBuffer result = new StringBuffer();
14 StringBuffer line = new StringBuffer();
15 boolean newline = false;
16 int end = 0;
17 while (m.find()) {
18 int start = m.start();
19 String token = s.substring(end, start);
20 end = m.end();
21 String match = s.substring(start, end);
22
23 if (line.length() != 0
24 && (line.length() + token.length()) > maxLineLength) {
25 result.append(line).append(BR);
26 line.delete(0, line.length());
27 } else if (!newline) {
28 line.append(' ');
29 }
30 line.append(token);
31
32 newline =
33 match.indexOf('\n') != -1
34 || match.toLowerCase().indexOf(BR) != -1;
35 if (newline) {
36 result.append(line).append(BR);
37 line.delete(0, line.length());
38 }
39 }
40 String token = s.substring(end);
41 if (!newline) {
42 line.append(' ');
43 }
44 line.append(token);
45 result.append(line);
46 return result.toString();
47 }
48
49 }