简体   繁体   English

比较2个字符串并返回匹配字母java的数量

[英]Compare 2 strings and return amount of matching letters java

How does one compare 2 Strings to return an int of amount matched in Java? 如何比较2个字符串以返回Java中匹配的数量的int?

I have a "lottery number" which is a UUID and looks like 561637ba-06f6-4457-9787-ba65768c1b73 I would compare it to another string like 72c92628-5789-4d5c-9287-742dbc57cca9 which excluding the - would be 5 matching characters. 我有一个“彩票号码”,它是一个UUID,看起来像561637ba-06f6-4457-9787-ba65768c1b73,我将其与另一个字符串(例如72c92628-5789-4d5c-9287-742dbc57cca9)进行比较,但不包括-将是5个匹配字符。 would there be a faster way that just simply looping through every single character? 有没有一种更快的方法可以简单地遍历每个字符?

Assuming that both strings have the same length, this is as good as it gets: 假设两个字符串具有相同的长度,那么就可以做到:

public static int numberMatchingChars(String s1, String s2) {
    int count = 0;
    for (int i = 0; i < s1.length(); i++)
        if (s1.charAt(i) == s2.charAt(i) && s1.charAt(i) != '-')
            count++;
    return count;
}

Clearly, you'll have to iterate over each char on both strings. 显然,您必须迭代两个字符串上的每个字符。

Not sure if this would improve matters or not and assuming that both strings have the same length and format, but anyway, technically you do not need to visit every char. 不知道这是否会改善问题,并假定两个字符串的长度和格式都相同,但是无论如何,从技术上讲,您不需要访问每个字符。

String arr1[] = s1.split ("-");
String arr2[] = s2.split ("-");

int totCount = 0;

for (int x = 0; x < arr1.length; x++) {

   if (arr1[x].equals (arr2[x]) == false) {

       // compare char by char for arr1[x] to arr2[x]
       totCount += numberMatchingChars(arr1[x], arr2[x]);

   }
}

public static int numberMatchingChars(String s1, String s2) {
    int count = 0;
    for (int i = 0; i < s1.length(); i++)
        if (s1.charAt(i) == s2.charAt(i))
            count++;
    return count;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM