Skip to content

Instantly share code, notes, and snippets.

@beall49
Last active April 23, 2019 16:28
Show Gist options
  • Save beall49/ae4fe5a0dba17f0813027b472a1b8ae0 to your computer and use it in GitHub Desktop.
Save beall49/ae4fe5a0dba17f0813027b472a1b8ae0 to your computer and use it in GitHub Desktop.
/**
* This should spit out a percentage of how close two strings are.
*/
public static Double stringCompare(String a, String b) {
if (a == null || b == null) {
return 0.0;
}
//Same string, no iteration needed.
if (a.equals(b)) {
return 100.0;
}
//One is empty, second is not
if ((a.length() == 0) || (b.length() == 0)) {
return 0.0;
}
double maxLen = a.length() > b.length() ? a.length() : b.length();
int minLen = a.length() < b.length() ? a.length() : b.length();
int sameCharAtIndex = 0;
//Compare char by char
for (int i = 0; i < minLen; i++) {
String aChar = String.valueOf(a.charAt(i));
String bChar = String.valueOf(b.charAt(i));
if (aChar.equals(bChar)) {
sameCharAtIndex++;
}
}
return sameCharAtIndex / maxLen * 100;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment