How to check if two equal-length strings are at least 25% 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.25;
    }
  
    public static void main(String[] args) {
        String str1 = "java c# sql c++ c python";
        String str2 = "java c# c php c++ python";
    
        if (are50PercentEqual(str1, str2)) {
            System.out.println("yes");
        } else {
            System.out.println("no");
        }
    }
}
  
  
  
/*
run:
  
yes
  
*/

 



answered May 11, 2024 by avibootz

Related questions

...