I created a Java program to compare two strings:
String str = "Hello&开发者_开发百科quot;;
if (str.equals("hello")) {
System.out.println("match");
} else {
System.out.println("no match");
}
It's case-sensitive. How can I change it so that it's not?
The best way is to use str.equalsIgnoreCase("foo")
. It's optimized specifically for this purpose.
You can also convert both strings to upper- or lowercase before comparing them with equals
. This is a trick that's useful to remember for other languages which might not have an equivalent of equalsIgnoreCase
.
str.toUpperCase().equals(str2.toUpperCase())
If you are using a non-Roman alphabet, take note of this part of the JavaDoc of equalsIgnoreCase
which says
Note that this method does not take locale into account, and will result in unsatisfactory results for certain locales. The Collator class provides locale-sensitive comparison.
Use String.equalsIgnoreCase()
.
Use the Java API reference to find answers like these:
https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#equalsIgnoreCase(java.lang.String)
https://docs.oracle.com/javase/1.5.0/docs/api/
String.equalsIgnoreCase
is the most practical choice for naive case-insensitive string comparison.
However, it is good to be aware that this method does neither do full case folding nor decomposition and so cannot perform caseless matching as specified in the Unicode standard. In fact, the JDK APIs do not provide access to information about case folding character data, so this job is best delegated to a tried and tested third-party library.
That library is ICU, and here is how one could implement a utility for case-insensitive string comparison:
import com.ibm.icu.text.Normalizer2;
// ...
public static boolean equalsIgnoreCase(CharSequence s, CharSequence t) {
Normalizer2 normalizer = Normalizer2.getNFKCCasefoldInstance();
return normalizer.normalize(s).equals(normalizer.normalize(t));
}
String brook = "flu\u0308ßchen";
String BROOK = "FLÜSSCHEN";
assert equalsIgnoreCase(brook, BROOK);
Naive comparison with String.equalsIgnoreCase
, or String.equals
on upper- or lowercased strings will fail even this simple test.
(Do note though that the predefined case folding flavour getNFKCCasefoldInstance
is locale-independent; for Turkish locales a little more work involving UCharacter.foldCase
may be necessary.)
You have to use the compareToIgnoreCase
method of the String
object.
int compareValue = str1.compareToIgnoreCase(str2);
if (compareValue == 0)
it means str1
equals str2
.
import java.lang.String; //contains equalsIgnoreCase()
/*
*
*/
String s1 = "Hello";
String s2 = "hello";
if (s1.equalsIgnoreCase(s2)) {
System.out.println("hai");
} else {
System.out.println("welcome");
}
Now it will output : hai
In the default Java API you have:
String.CASE_INSENSITIVE_ORDER
So you do not need to rewrite a comparator if you were to use strings with Sorted data structures.
String s = "some text here";
s.equalsIgnoreCase("Some text here");
Is what you want for pure equality checks in your own code.
Just to further informations about anything pertaining to equality of Strings in Java. The hashCode() function of the java.lang.String class "is case sensitive":
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
So if you want to use an Hashtable/HashMap with Strings as keys, and have keys like "SomeKey", "SOMEKEY" and "somekey" be seen as equal, then you will have to wrap your string in another class (you cannot extend String since it is a final class). For example :
private static class HashWrap {
private final String value;
private final int hash;
public String get() {
return value;
}
private HashWrap(String value) {
this.value = value;
String lc = value.toLowerCase();
this.hash = lc.hashCode();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o instanceof HashWrap) {
HashWrap that = (HashWrap) o;
return value.equalsIgnoreCase(that.value);
} else {
return false;
}
}
@Override
public int hashCode() {
return this.hash;
}
}
and then use it as such:
HashMap<HashWrap, Object> map = new HashMap<HashWrap, Object>();
Note that you may want to do null checks on them as well prior to doing your .equals or .equalsIgnoreCase.
A null String object can not call an equals method.
ie:
public boolean areStringsSame(String str1, String str2)
{
if (str1 == null && str2 == null)
return true;
if (str1 == null || str2 == null)
return false;
return str1.equalsIgnoreCase(str2);
}
Use s1.equalsIgnoreCase(s2)
: https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#equalsIgnoreCase(java.lang.String).
You can use equalsIgnoreCase
More about string can be found in String Class and String Tutorials
To be nullsafe, you can use
org.apache.commons.lang.StringUtils.equalsIgnoreCase(String, String)
or
org.apache.commons.lang3.StringUtils.equalsIgnoreCase(CharSequence, CharSequence)
public boolean newEquals(String str1, String str2)
{
int len = str1.length();
int len1 = str2.length();
if(len==len1)
{
for(int i=0,j=0;i<str1.length();i++,j++)
{
if(str1.charAt(i)!=str2.charAt(j))
return false;
}`enter code here`
}
return true;
}
精彩评论