|
| 1 | +import java.util.Scanner; |
| 2 | + |
| 3 | +class LexicographicString { |
| 4 | + // Main method |
| 5 | + public static void main(String[] args) { |
| 6 | + Scanner input = new Scanner(System.in); |
| 7 | + |
| 8 | + System.out.print("Enter first string: "); |
| 9 | + String str1 = input.nextLine(); |
| 10 | + |
| 11 | + System.out.print("Enter second string: "); |
| 12 | + String str2 = input.nextLine(); |
| 13 | + |
| 14 | + // Method to compare two strings lexicographically |
| 15 | + int result = compareStrings(str1, str2); |
| 16 | + |
| 17 | + // Display result |
| 18 | + if (result < 0) { |
| 19 | + System.out.printf("\"%s\" comes before \"%s\" in lexicographical order", str1, str2); |
| 20 | + } else if (result > 0) { |
| 21 | + System.out.printf("\"%s\" comes before \"%s\" in lexicographical order", str2, str1); |
| 22 | + } else { |
| 23 | + System.out.printf("\"%s\" and \"%s\" are equal in lexicographical order", str1, str2); |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + // Method to compare two strings lexicographically |
| 28 | + public static int compareStrings(String str1, String str2) { |
| 29 | + int len1 = str1.length(); |
| 30 | + int len2 = str2.length(); |
| 31 | + int minLen = Math.min(len1, len2); |
| 32 | + |
| 33 | + for (int i = 0; i < minLen; i++) { |
| 34 | + if (str1.charAt(i) != str2.charAt(i)) { |
| 35 | + return str1.charAt(i) - str2.charAt(i); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + return len1 - len2; |
| 40 | + } |
| 41 | +} |
0 commit comments