1

我目前使用此代码将行限制为 20 个字符:

if (string.length() % 20 == 0 && string.length() >= 20) {
    this.string += "\n";
}

但是,它会破坏这样的单词:

Hello, my name is Pa
trick

我怎样才能防止这种情况?

4

3 回答 3

9

您可以使用这样的正则表达式.{1,20}(\W|$)来拆分接近 20 个字符但不拆分单词的短语。

这将适用于最多 20 个字符。如果你想配置数字,你可以在正则表达式中参数化它,比如你的限制"(.{1," + max + "}(\\W|$))"在哪里。max

String s = "Hello, my name is Patrick and I have a lot to say, but I will tell you that another day.";
Matcher m = Pattern.compile("(.{1,20}(\\W|$))").matcher(s);
StringBuilder b = new StringBuilder();
while (m.find()) {
    b.append(m.group()).append("\n");
}
System.out.println("-> " + b.toString());

将打印出:

-> Hello, my name is 
Patrick and I have a 
lot to say, but I 
will tell you that 
another day.

编辑

我编辑了上面的答案,实际上它正在搜索一个不在单词中的字符\W,在我的示例中,字符串以 a 结尾.但不在你的字符串中。我编辑了上面的正则表达式,因此如果字符串确实以未表示的字符结尾,则它也可以通过在字符串末尾\W添加条件来表示$

你可以在这里看到一个可运行的例子:http: //ideone.com/Nw2aNr

于 2012-12-05T17:01:33.573 回答
3

用空格分割字符串,s.split("\\s+")然后逐字附加,观察 line 的长度。

于 2012-12-05T16:56:33.387 回答
1

我想这是每次附加一个字符时的一段代码。所以,要解决这个问题,你应该做一些更有趣的事情。基本思想是这样的:

  1. 检测到线路限制。
  2. 拿最后一行。
  3. 使用空格分割String words[] = line.split("\\s+");
  4. 如果你有多个单词,那么
    • 使用 获取该行的子字符串lastIndexOf(words[words.length - 1]);,这样可以保留除最后一个单词之外的所有内容。
    • 将最后一个单词添加到新行。
  5. 否则,像现在一样断开单词(通过添加换行符)
于 2012-12-05T17:02:36.490 回答