如何比较两个 char 数组比较相同时间顺序中的字符但给出一个代表每个可能符号的额外符号?

How to compare two char arrays comparing characters in the same chronology but given an extra sign which stands for every possible sign?

char [] text = {'H','e','l','L','o','H','e','l','L','o'};
char[] pat = {'H','e','?','l','o'}; //'?' stands for every possible sign

我们可以忽略字母是大写还是小写。 现在我需要输出它发生的频率。

Output:  He?lo is in HelLoHelLo 2x

我知道您可以使用 "contain" 之类的字符串方法,但我该如何考虑问号?

我天真地实现它的方式,没有考虑太多

  • 创建 inputIndex 并将其设置为 0
  • 创建 matchIndex 并将其设置为 0
  • 通过递增 inputIndex 一个一个地迭代输入
    • 比较 inputIndex 输入中的字符与 matchIndex
    • 匹配中的字符
    • 如果他们 "match" 将 matchIndex 递增一 - 如果他们没有将 matchIndex 设置为 0
    • 如果 matchIndex 等于您的 pat 长度,则将实际匹配数增加 1,并将 matchIndex 设置回 0

我写 "match" 的地方你需要实现 你的 自定义匹配逻辑,忽略大小写,如果这个地方的模式是 ?.

@Test
public void match() {
    char [] text = {'H','e','l','L','o','H','e','l','L','o'};
    char[] pat = {'H','e','?','l','o'}; //'?' stands for every possible sign
    printMatch(text, pat);
}

private void printMatch(char[] text, char[] pat) {
    String textStr = new String(text);
    String patStr = new String(pat);
    final String regexPattern = patStr.replace('?', '.').toLowerCase();
    final Pattern pattern = Pattern.compile(regexPattern);
    final Matcher matcher = pattern.matcher(textStr.toLowerCase());
    while (matcher.find()) {
        System.out.println(patStr + " is in " + textStr );
    }
}

这个呢?

static int countPatternOccurences (char [] text, char [] pat)
{
    int i = 0;
    int j = 0;
    int k = 0;
            while ( i < text.length)
            {
                int a = Character.getNumericValue(pat[j]);
                int b = Character.getNumericValue(text[i]);


                if (a == b || pat[j] =='?')
                {
                    j++;

                }
                else
                {
                    j=0;
                    //return 0;
                }
                if(j == pat.length)
                {
                    k++;
                    j = 0;
                }
                i++;
            }
            return k; // returns occurrences of pat in text
        }
public int matchCount(char[] text, char[] pattern) {
    int consecCharHits = 0, matchCount = 0;

    for (int i = 0; i < text.length; i++) {
        if (text[i] == pattern[consecCharHits] || '?' == pattern[consecCharHits]) { // if char matches
            consecCharHits++;
            if (consecCharHits == pattern.length) { // if the whole pattern matches
                matchCount++;
                i -= consecCharHits - 1; // return to the next position to be evaluated
                consecCharHits = 0; // reset consecutive char hits
            }
        } else {
            i -= consecCharHits;
            consecCharHits = 0;
        }
    }
    return matchCount;
}