Monday, November 18, 2024
Google search engine
HomeData Modelling & AICompare two strings lexicographically in Java

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:

  1. if (string1 > string2) it returns a positive value.
  2. if both the strings are equal lexicographically i.e.(string1 == string2) it returns 0.
  3. if (string1 < string2) it returns a negative value.

Java




// Java program to show how to compare Strings 
// using library function 
public class Test 
    public static void main(String[] args) 
    
        String s1 = "Ram"
        String s2 = "Ram"
        String s3 = "Shyam"
        String s4 = "ABC"
  
        System.out.println(" Comparing strings with compareTo:"); 
        System.out.println(s1.compareTo(s2)); 
        System.out.println(s1.compareTo(s3)); 
        System.out.println(s1.compareTo(s4)); 
    


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. 

Java




// Java program to Compare two strings 
// lexicographically 
class Compare { 
  
    // This method compares two strings 
    // lexicographically without using 
    // library functions 
    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); 
            
        
  
        // Edge case for strings like 
        // String 1="Geeky" and String 2="Geekyguy" 
        if (str1.length() < str2.length()) { 
            return (str1.length()-str2.length()); 
        
        else if (str1.length() > str2.length()) { 
            return (str1.length()-str2.length()); 
        
          
        // If none of the above conditions is true, 
        // it implies both the strings are equal 
        else
            return 0
        
    
  
    // Driver function to test the above program 
    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("Geeksforneveropen"); 
      
        System.out.println(stringCompare(string1, 
                                        string2)); 
        System.out.println(stringCompare(string1, 
                                        string3)); 
        System.out.println(stringCompare(string2, 
                                        string1)); 
  
        // To show for edge case 
        // In these cases, the output is the difference of 
        // length of the string 
        System.out.println(stringCompare(string1, 
                                        string4)); 
        System.out.println(stringCompare(string4, 
                                        string1)); 
    


Output

-9
0
9
-8
8

Time Complexity: O(n)
Auxiliary Space: O(1)

This article is contributed by Ankit Jain . If you like neveropen and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the neveropen main page and help other Geeks. 

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments