在构成该文本的片段数组列表中查找文本片段(文本中的选择)的最佳方法是什么?



我在 arraylist 上查找文本巧合时遇到麻烦。我有这个结构:

public class Fragment {
private int id;
private Date date;
private String text;
private Profile profile;
}

我有和活动从 API 获取片段列表并将它们放在ArrayList<Fragment>上。 它还创建了一个包含所有片段的文本视图。然后我有一个自定义ActionMode.Callback,用于显示"搜索"等上下文菜单选项。

单击"搜索"菜单选项时,我想在该片段列表中搜索与所选文本的重合,但文本不能是完全重合的片段。例如,在列表中包含以下片段:

fragments.get(0).getText() //returns "Hi"
fragments.get(1).getText() //returns ", Mi name is Peter"
fragments.get(2).getText() //returns ", how are you?"

选择的文本是"是彼得,怎么样">

感谢您的任何建议!

下面是一个如何做到这一点的示例。它基本上创建了一个边界,其中基于全文进行匹配,并找到与此边界重叠的片段。为了澄清,我添加了一些评论。

//Set up an example arraylist
ArrayList<Fragment> fragments = new ArrayList<>();
fragments.add(new Fragment("Hi"));
fragments.add(new Fragment(", My name is Peter"));
fragments.add(new Fragment(", how are you?"));
//Create a full string of all fragments together
String total = fragments.stream().map(Fragment::getText).collect(Collectors.joining());
String toMatch = "Peter, how";
//Search and check for a match in the full string, store the index where the match starts
int matchIndex = total.indexOf(toMatch);
if (matchIndex >= 0) {
//Store the index where the match ends
int maxMatchIndex = matchIndex + toMatch.length();
ArrayList<Fragment> overlap = new ArrayList<>();
//Keep track of the current character index we're at compared to the full string
int processed = 0;
for (Fragment fragment : fragments) {
//Add any fragments that lie between the start and end index of the match to the overlap arraylist
if(processed + fragment.getText().length() >= matchIndex && processed < maxMatchIndex) {
overlap.add(fragment);
}
//Add the length of the processed fragment to update the "full string index" for the next check
processed += fragment.getText().length();
}
//Do something with the match, here we just print the text
for (Fragment l : overlap) {
System.out.println("Fragment match: " + l.getText());
//Prints:
//  Fragment match: , My name is Peter
//  Fragment match: , how are you?
}
}

请注意,我创建了一个用于插入文本的基本构造函数和一个用于比较文本的 getter。

最新更新