Compare two strings lexicographically in Java
In this article, we will discuss how we can compare two strings lexicographically in Java. One solution is to use Java compareTo() method. The method compareTo() is used for comparing two strings lexicographically in Java. Each character of both the strings is converted into a Unicode value for comparison.
int compareTo(String str) :
It returns the following values:
- if (string1 > string2) it returns a positive value.
- if both the strings are equal lexicographically i.e.(string1 == string2) it returns 0.
- if (string1 < string2) it returns a negative value.
Java
class Compare {
public static int stringCompare(String str1,
String str2)
{
for ( int i = 0 ; i < str1.length() &&
i < str2.length(); i++) {
if (( int )str1.charAt(i) ==
( int )str2.charAt(i)) {
continue ;
}
else {
return ( int )str1.charAt(i) -
( int )str2.charAt(i);
}
}
if (str1.length() < str2.length()) {
return (str1.length()-str2.length());
}
else if (str1.length() > str2.length()) {
return (str1.length()-str2.length());
}
else {
return 0 ;
}
}
public static void main(String args[])
{
String string1 = new String( "Geeks" );
String string2 = new String( "Practice" );
String string3 = new String( "Geeks" );
String string4 = new String( "Geeksforgeeks" );
System.out.println(stringCompare(string1,
string2));
System.out.println(stringCompare(string1,
string3));
System.out.println(stringCompare(string2,
string1));
System.out.println(stringCompare(string1,
string4));
System.out.println(stringCompare(string4,
string1));
}
}
|
Output
Comparing strings with compareTo:
0
-1
17
Time Complexity: O(N)
Auxiliary Space: O(1)
Refer How to Initialize and Compare Strings in Java? for more details. How to compare two strings without using library function?
1. Input two strings string 1 and string 2.
2. for (int i = 0; i < str1.length() &&
i < str2.length(); i ++)
(Loop through each character of both
strings comparing them until one
of the string terminates):
a. If unicode value of both the characters
is same then continue;
b. If unicode value of character of
string 1 and unicode value of string 2
is different then return (str1[i]-str2[i])
3. if length of string 1 is less than string2
return str2[str1.length()]
else
return str1[str2.length()]
Below is the implementation of the above algorithm.
Time Complexity: O(n)
Auxiliary Space: O(1)
Last Updated :
18 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...