在Android中匹配多个字符串

时间:2019-02-13 11:37:15

标签: java android string

我有三个琴弦

字符串1 =“你好,你过得怎么样”

字符串2 =“你好,你好吗”

字符串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

任何人都可以帮助我。我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

你可以有这样的东西:

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++;
        }
    }
}