BreakIterator
可用于查找字符、单词、行和句子之间可能的中断。这对于在可见字符中移动光标、双击选择单词、三次单击选择句子和换行等操作很有用。
样板代码
以下代码用于以下示例。只需调整第一部分以更改BreakIterator
.
// change these two lines for the following examples
String text = "This is some text.";
BreakIterator boundary = BreakIterator.getCharacterInstance();
// boiler plate code
boundary.setText(text);
int start = boundary.first();
for (int end = boundary.next(); end != BreakIterator.DONE; end = boundary.next()) {
System.out.println(start + " " + text.substring(start, end));
start = end;
}
如果您只是想对此进行测试,您可以将其直接粘贴到onCreate
Android 中的 Activity 中。我正在使用System.out.println
而不是Log
这样它也可以在纯 Java 环境中进行测试。
我使用的java.text.BreakIterator
是 ICU 而不是 ICU ,它只能从 API 24 获得。有关更多信息,请参阅底部的链接。
人物
更改样板代码以包含以下内容
String text = "Hi 中文éé\uD83D\uDE00\uD83C\uDDEE\uD83C\uDDF3.";
BreakIterator breakIterator = BreakIterator.getCharacterInstance();
输出
0 H
1 i
2
3 中
4 文
5 é
6 é
8
10
14 .
最感兴趣的部分是索引6
、8
和10
。您的浏览器可能会或可能不会正确显示字符,但用户会将所有这些字符解释为单个字符,即使它们由多个 UTF-16 值组成。
字
更改样板代码以包括以下内容:
String text = "I like to eat apples. 我喜欢吃苹果。";
BreakIterator boundary = BreakIterator.getWordInstance();
输出
0 I
1
2 like
6
7 to
9
10 eat
13
14 apples
20 .
21
22 我
23 喜欢
25 吃
26 苹果
28 。
这里有一些有趣的事情需要注意。首先,在空格的两侧检测到断字。其次,即使有不同的语言,仍然可以识别多字汉字。即使我将语言环境设置为Locale.US
.
线条
您可以保持与 Words 示例相同的代码:
String text = "I like to eat apples. 我喜欢吃苹果。";
BreakIterator boundary = BreakIterator.getLineInstance();
输出
0 I
2 like
7 to
10 eat
14 apples.
22 我
23 喜
24 欢
25 吃
26 苹
27 果。
请注意,中断位置不是整行文本。它们只是换行文本的方便位置。
输出类似于 Words 示例。但是,现在空格和标点符号包含在它之前的单词中。这是有道理的,因为您不希望新行以空格或标点符号开头。另请注意,中文字符会为每个字符换行。这与中文可以跨行断行的事实是一致的。
句子
更改样板代码以包括以下内容:
String text = "I like to eat apples. My email is me@example.com.\n" +
"This is a new paragraph. 我喜欢吃苹果。我不爱吃臭豆腐。";
BreakIterator boundary = BreakIterator.getSentenceInstance();
输出
0 I like to eat apples.
22 My email is me@example.com.
50 This is a new paragraph.
75 我喜欢吃苹果。
82 我不爱吃臭豆腐。
在多种语言中识别出正确的断句。此外,电子邮件域中的点也没有误报。
笔记
您可以在创建 时设置LocaleBreakIterator
,但如果不这样做,它只会使用默认 locale。
进一步阅读