gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:43:11 24 4
gpt4 key购买 nike

我在数组列表上寻找文本重合时遇到了麻烦。我有这样的结构:

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

我有一个从 API 获取 fragment 列表并将它们放在 ArrayList<Fragment> 上的 Activity 。它还创建一个包含所有 fragment 的 TextView。然后我有一个自定义ActionMode.Callback用于显示上下文菜单选项,例如“搜索”。

当单击“搜索”菜单选项时,我想在该 fragment 列表中搜索与所选文本的重合,但该文本不可能是完全重合的 fragment 。例如,将此 fragment 放在列表中:

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

选择的文本是“is peter, how are”

感谢您的建议!

最佳答案

这里是一个如何做到这一点的示例。它基本上根据全文创建了一个匹配发生的边界,并找到与该边界重叠的 fragment 。我添加了一些评论以进行澄清。

//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 来比较文本。

关于java - 在组成该文本的 fragment 数组列表中查找文本 fragment (文本中的选择)的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58484047/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com