Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save gauravkukade/93fdb78e91c522df756f2ef912c6b357 to your computer and use it in GitHub Desktop.
Save gauravkukade/93fdb78e91c522df756f2ef912c6b357 to your computer and use it in GitHub Desktop.
A Java program to compare two strings lexicographically by creating user defined function. It is embedded at https://coderolls.com/compare-two-strings-lexicographically-in-java
/**
* The Java program to compare two strings lexicographically
* by creating user defined function.
*
* @author Gaurav Kukade at coderolls.com
*/
public class CompareLexicographicallyWithUserDefinedFunction {
public static void main(String[] args) {
String firstString = "Paneer";
String secondString = "Paneer";
String thirdString = "Butter";
String fourthString = "Cheese";
String fifthString = "PaneerButter";
System.out.println("Comparing two strings lexicographically by user defined function");
System.out.print("\nCompairing firstString ("+firstString+") to the secondString ("+secondString+") returns: ");
System.out.println(compareString(firstString, secondString));
System.out.print("\nCompairing secondString ("+secondString+") to the thirdString ("+thirdString+") returns: ");
System.out.println(compareString(secondString, thirdString));
System.out.print("\nCompairing thirdString ("+thirdString+") to the fourthString ("+fourthString+") returns: ");
System.out.println(compareString(thirdString, fourthString));
System.out.print("\nCompairing fourthString ("+fourthString+") to the firstString ("+firstString+") returns: ");
System.out.println(compareString(fourthString, firstString));
// Edge case comparing Paneer & PaneerButter
System.out.print("\nCompairing firstString ("+firstString+") to the fifthString ("+fifthString+") returns: ");
System.out.println(compareString(firstString, fifthString));
}
/*
* User defined function to compare two string lexicographically
*/
public static int compareString(String str, String argumentString) {
int lim= Math.min(str.length(), argumentString.length());
int k=0;
while(k<lim) {
if(str.charAt(k)!= argumentString.charAt(k)) {
return (int) str.charAt(k)- argumentString.charAt(k);
}
k++;
}
return str.length() - argumentString.length();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment