gpt4 book ai didi

java - 在 Android 中匹配多个字符串

转载 作者:行者123 更新时间:2023-11-30 05:05:19 25 4
gpt4 key购买 nike

我有三个字符串

String 1= "你好,今天过得怎么样"

String 2= "你好,你好吗"

String 3="今天过得怎么样"

我想将字符串 2 的每个单词与字符串 1 匹配,并相应地更改单词的颜色。我使用了下面的代码并且工作正常

private void printDiff(final Context context, String sentence1, String sentence2) {
String[] array1 = sentence1.split(" ");
String[] array2 = sentence2.split(" ");

SpannableStringBuilder sb = new SpannableStringBuilder(sentence1);
for (int i = 0; i < array1.length; i++) {
int colorRes;
if (i < array2.length) {

colorRes = array1[i].equalsIgnoreCase(array2[i]) ? R.color.colorPrimary : R.color.colorAccent;


} else {
colorRes = R.color.black;
}
int startIndex = getStartIndexOf(array1, i);
int endIndex = startIndex + array1[i].length();
sb.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, colorRes)), startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}


}

public static int getStartIndexOf(String[] array, int index) {
int count = 0;
for (int i = 0; i < index; i++) {
count += array[i].length();
count++;
}
return count;
}

您可以在下图中看到输出

enter image description here

现在我想将字符串 3 与字符串 1 匹配,我希望输出如下图所示,因为字符串 2 和字符串 1 已​​经匹配。

enter image description here

谁能帮帮我。我不知道该怎么做。

最佳答案

你可以有这样的东西:

String text;
String[] pattern;

int matchedSoFar = 0;

while(matchedSoFar < text.length) {
for(int i = 0; matchedSoFar < text.length and i < pattern.length; i++) {
for(int j = 0; matchedSoFar < text.length and j < pattern[i].length; j++) {
// set color if pattern[i][j] == text[matchedSoFar]
matchedSoFar++;
}
}
}

关于java - 在 Android 中匹配多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54669257/

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