How to check if two equal-length strings are at least 75% equal in Java

1 Answer

0 votes
class program {
    public static boolean are50PercentEqual(String str1, String str2) {
        if (str1 == null || str2 == null || str1.length() != str2.length()) {
            return false;
        }
     
        int matchingChars = 0;
       
        for (int i = 0; i < str1.length(); i++) {
            if (str1.charAt(i) == str2.charAt(i)) {
                matchingChars++;
            }
        }

        return (double) matchingChars / str1.length() >= 0.75;
    }
 
    public static void main(String[] args) {
        String str1 = "java c# c c++ sql python";
        String str2 = "java c# c c++ php python";
   
        if (are50PercentEqual(str1, str2)) {
            System.out.println("yes");
        } else {
            System.out.println("no");
        }
    }
}
 
 
 
/*
run:
 
yes
 
*/

 

 



answered May 11, 2024 by avibootz

Related questions

...