我在arraylist上查找文本重合时遇到麻烦。我有这个结构:
public class Fragment {
private int id;
private Date date;
private String text;
private Profile profile;
}
我有一个从API获取片段列表并将其放在
ArrayList<Fragment>
上的活动。并且还会创建一个包含所有片段的TextView。然后,我有一个自定义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来比较文本。