자바 스크립트 compareTo - jaba seukeulibteu compareTo

자바 스크립트 compareTo - jaba seukeulibteu compareTo

You may want to compare two strings to know which is higher or lower alphabetically or to see if they are equal.

You can do this in many ways. I'll show you two of them in this article.

1. How to Compare Strings Using localeCompare

You can use the localeCompare method to compare two strings in the current locale. Here's the syntax:

string1.localeCompare(string2)

locaelCompare returns:

  • 1 if string1 is greater (higher in the alphabetical order) than string2
  • -1 if string1 is smaller (lower in the alphabetical order) than string2
  • 0 if string1 and string2 are equal in the alphabetical order

Here are some examples comparing two strings:

const string1 = "hello"
const string2 = "world"

const compareValue = string1.localeCompare(string2)
// -1

It gives -1 because, in the English locale, h in hello comes before w in the world (w is further down in the alphabetical order than h)

Another example:

const string1 = "banana"
const string2 = "back"

const compareValue = string1.localeCompare(string2)
// 1

The comparison above gives 1 because, in the English locale, ban in banana comes after bac in back.

One more example:

const string1 = "fcc"
const string2 = "fcc"
const string3 = "Fcc"

const compareValue1 = string1.localeCompare(string2)
// 0

const compareValue2 = string1.localeCompare(string3)
// -1

Comparing "fcc" and "fcc" gives 0 because they are equal in order. "fcc" and "Fcc" gives -1 because capital "F" is greater than small "f".

In some browsers, instead of -1, it may return -2 or some other negative value. So, do not depend on -1 or 1, instead on negative (less than 0) or positive (more than 0) values

2. How to Compare Strings Using Mathematical Operators

You can also use mathematical operators like greater than (>), less than (<), and equal to when comparing strings.

Mathematical operators work similarly to localeCompare – by returning results based on the order of the characters in the string.

Using the previous examples:

const string1 = "hello"
const string2 = "world"

console.log(string1 > string2)
// false

string1 is not greater than string2, because h comes before w, so it is less than.

For the other example:

const string1 = "banana"
const string2 = "back"

console.log(string1 > string2)
// true

string1 is greater than string2 because ban comes after back.

And for the last example:

const string1 = "fcc"
const string2 = "fcc"
const string3 = "Fcc"

console.log(string1 === string2)
// true

console.log(string1 < string3)
// false

string1 is equal to (===) string2, but string1 is not less than string3, which is in contrast to localeCompare.

With mathematical operators, "fcc" is greater than "Fcc", but with localeCompare, "fcc".localeCompare("Fcc")" returns -1 to show that "fcc" is less than "Fcc".

This behavior is one reason why I don't recommend using mathematical operators for comparing strings, even though it has the potential to do so.

Another reason why I don't recommend using mathematical operators is because "fcc" > "fcc" and "fcc" < "fcc" is false. "fcc" is equal to "fcc". So if you're depending on mathematical operators, getting false may be for different reasons than you believe.

So, for comparing strings, amongst the many ways there may be, using localCompare is an effective approach because it can be used for different languages.

Now you know an easy way to compare strings. Happy coding!



Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Strings in Java are objects that are supported internally by a char array. Since arrays are immutable, and strings are also a type of exceptional array that holds characters, therefore, strings are immutable as well. 

The String class of Java comprises a lot of methods to execute various operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), substring() etc. Out of these methods, we will be focusing on the compareTo() method. 

String.compareTo() Method

The Java String class compareTo() method compares the given string with the current string lexicographically. It returns a positive number, negative number, or 0. It compares strings on the basis of the Unicode value of each character in the strings.

If the first string is lexicographically greater than the second string, it returns a positive number (difference of character value). If the first string is less than the second string lexicographically, it returns a negative number, and if the first string is lexicographically equal to the second string, it returns 0.

Note: 

  • if string1 > string2, it returns positive number  
  • if string1 < string2, it returns negative number  
  • if string1 == string2, it returns 0  

There are three variants of the compareTo() method. This article depicts all of them, as follows 

1. int compareTo(Object obj)

This method compares this String to another Object. 

Syntax: 

int compareTo(Object obj)

Parameters: 

  • obj: the Object to be compared.

Return Value: The value 0 if the argument is a string lexicographically equal to this string; a value less than 0 if the argument is a string lexicographically greater than this string; and a value greater than 0 if the argument is a string lexicographically less than this string.

Java

public class Cmp1 {

    public static void main(String args[])

    {

        String str1 = "geeksforgeeks";

        String str2 = new String("geeksforgeeks");

        String str3 = new String("astha");

        System.out.print(

            "Difference of geeksforgeeks(obj) and geeksforgeeks(str) : ");

        System.out.println(str1.compareTo(str2));

        System.out.print(

            "Difference of astha(obj) and geeksforgeeks(str) : ");

        System.out.println(str1.compareTo(str3));

    }

}

Output

Difference of geeksforgeeks(obj) and geeksforgeeks(str) : 0
Difference of astha(obj) and geeksforgeeks(str) : 6

2. int compareTo(String anotherString) 

This method compares two strings lexicographically. 

Syntax: 

int compareTo(String anotherString)

Parameters: 

  • anotherString:  the String to be compared.

Return Value: The value 0 if the argument is a string lexicographically equal to this string; a value less than 0 if the argument is a string lexicographically greater than this string; and a value greater than 0 if the argument is a string lexicographically less than this string.

Java

public class Cmp2 {

    public static void main(String args[])

    {

        String str1 = "geeksforgeeks";

        String str2 = "geeksforgeeks";

        String str3 = "astha";

        System.out.print(

            "Difference of geeksforgeeks(str) and geeksforgeeks(str) : ");

        System.out.println(str1.compareTo(str2));

        System.out.print(

            "Difference of astha(str) and geeksforgeeks(str) : ");

        System.out.println(str1.compareTo(str3));

    }

}

Output

Difference of geeksforgeeks(str) and geeksforgeeks(str) : 0
Difference of astha(str) and geeksforgeeks(str) : 6

3. int compareToIgnoreCase(String str)  

This method compares two strings lexicographically, ignoring case differences. 

Syntax:

int compareToIgnoreCase(String str)

Parameters: 

  • str: the String to be compared.

Return Value: This method returns a negative integer, zero, or a positive integer as the specified String is greater than, equal to, or less than this String, ignoring case considerations.

Java

public class Cmp3 {

    public static void main(String args[])

    {

        String str1 = "geeks";

        String str2 = "gEEkS";

        System.out.print(

            "Difference of geeks and gEEkS (case sensitive) : ");

        System.out.println(str1.compareTo(str2));

        System.out.print(

            "Difference of geeks and gEEkS (case insensitive) : ");

        System.out.println(str1.compareToIgnoreCase(str2));

    }

}

Output

Difference of geeks and gEEkS (case sensitive) : 32
Difference of geeks and gEEkS (case insensitive) : 0

This article is contributed by Astha Tyagi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above