Comparing Strings in a Locale-Independent Way


 

Comparing Strings in a Locale-Independent Way

In this section, you will learn how to compare strings in a locale independent way.

In this section, you will learn how to compare strings in a locale independent way.

Comparing Strings in a Locale-Independent Way

In this section, you will learn how to compare strings in a locale independent way.

For handling strings, java.text.* package provides the class Collator. This class performs locale-sensitive String comparison, or you can say, it allows to perform string comparisons for different languages. You can also use this class for searching and sorting.

In the given example, we have instantiate the Collator class by invoking the getInstance() method and specify a locale using Locale class. Then we have called the method compare() of Collator class to perform a locale-independent string comparison. This method returns negative value if the first string argument is less than second, positive value if first string argument is greater then second and 0 if the first string argument is equal to second one.

Here is the code:

import java.text.*;
import java.util.*;

public class CompareStringUsingCollator {
	public static void main(String[] args) {
		Collator col = Collator.getInstance(new Locale("en", "US"));
		int i = col.compare("rose", "india");
		System.out.println(i);
	}
}

Ads