📜  java lexographic - Java (1)

📅  最后修改于: 2023-12-03 15:15:56.834000             🧑  作者: Mango

Java Lexicographic

When working with strings in Java, lexicographic order is often required. This refers to the way that strings are ordered based on the alphabetical order of their characters.

Sorting Strings in Lexicographic Order

To sort an array of strings in lexicographic order, we can use the Arrays.sort() method in Java.

String[] fruits = {"apple", "banana", "orange", "pear"};
Arrays.sort(fruits); // sorts the array in lexicographic order

This will result in the fruits array being sorted in ascending order based on the alphabetical order of the words.

Comparing Strings in Lexicographic Order

To compare two strings in Java based on lexicographic order, we can use the String.compareTo() method.

String s1 = "apple";
String s2 = "banana";
int result = s1.compareTo(s2); // result will be negative as "a" comes before "b" in the alphabet

If s1 comes before s2 in lexicographic order, then result will be a negative number. If s1 comes after s2, then result will be a positive number. If the two strings are equal in lexicographic order, then result will be 0.

Conclusion

Lexicographic order is an important concept when working with strings in Java. To sort an array of strings in lexicographic order, use the Arrays.sort() method. To compare two strings based on lexicographic order, use the String.compareTo() method.