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

标签 java android string

我有三个字符串

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/

相关文章:

java - 使用 jdom 创建 xml,如何设置独立的 ="no"属性

java - 股票价格的简单移动平均线

java - 创建onrequest权限granted()时传递的grant result是什么

java - 在我的应用程序中显示特定通知消息时出现问题

Android - requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS) 做什么?

正则表达式 - 基于匹配内值的匹配长度(使用变量?)

java - 添加到以下字符串的空格分隔符

android - 如何从android中的代码知道路由器的IP地址?

Android GPS 精度甚至不及内置 map 应用程序

c# - 测试 NULL 并在需要时返回一个字符串 - 优点/缺点是什么