How to compare two strings lexicographically in Java
Let’s learn how to compare two strings lexicographically in Java.
Before proceeding with the tutorial let us understand the term ‘lexicographically‘.
Lexicographic order is the way of arranging/ordering the words on the basis of the alphabetical order of the letters/alphabets contained in them. It is also known as the dictionary order, since the words arranged in dictionary are arranged in lexicographic order.
Java provides an in-built method named compareTo().
compareTo() function in Java
This can be used for comparing two strings lexicographically where each character of the strings is converted to a Unicode(ASCII) value for comparison. It returns ‘int’ type value.
int String1.compareTo(String2)
It returns the following values in the given scenarios, given two strings s1 and s2:
- If s1>s2 then it returns a value greater than zero;
- else if, s1==s2 then it returns value equal to zero;
- else if s1<s2 then it returns the value less than zero.
Working to compareTo() function
Let the strings are s1 and s2 and the syntax goes like this:
s1.compareTo(s2)
Here, string s2 is compared to string s1.
Some basic ASCII values are
- space : 32
- [A-Z] : [65-90]
- [a-z] : [97-122]
- [0-9] : [48-57]
Implementation
//Java program to compare the strings lexicographically public class Comp { public static void main(String[] args) { System.out.println("Comparing two strings lexicographically"); System.out.println("abc".compareTo("xyz"));//-23 System.out.println("hello".compareTo("world"));//-15 System.out.println("acde".compareTo("abde"));//1 System.out.println("aabcde".compareTo("abbcde"));//-1 System.out.println("123".compareTo("987"));//-8 System.out.println("012".compareTo("01234"));//-2 System.out.println("999".compareTo("111"));//8 System.out.println("0000".compareTo("0101"));//-1 System.out.println("abc123".compareTo("123abc"));//48 System.out.println("xyz999".compareTo("000xyz"));//72 } }
Output
-23 -15 1 -1 -8 -2 8 -1 48 72
Hope that this tutorial helps you better understand how to compare two strings lexicographically and the working of compareTo()
method.
Leave a Reply