Java 如何使我的字符串比较不区分大小写?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2220400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 04:51:59  来源:igfitidea点击:

How do I make my string comparison case insensitive?

javastringcomparisoncase-insensitive

提问by user268018

I created a Java program to compare two strings:

我创建了一个 Java 程序来比较两个字符串:

String s1 = "Hello";
String s2 = "hello";

if (s1.equals(s2)) {
    System.out.println("hai");
} else {
    System.out.println("welcome");
}

It displays "welcome". I understand it is case sensitive. But my problem is that I want to compare two strings without case sensitivity. I.e. I expect the output to be hai.

它显示“欢迎”。我知道它区分大小写。但我的问题是我想比较两个不区分大小写的字符串。即我希望输出为hai.

回答by Michael Bavin

  • The best would be using s1.equalsIgnoreCase(s2): (see javadoc)
  • You can also convert them both to upper/lower case and use s1.equals(s2)
  • 最好的方法是使用s1.equalsIgnoreCase(s2):( 请参阅javadoc)
  • 您还可以将它们都转换为大写/小写并使用 s1.equals(s2)

回答by codaddict

You can use equalsIgnoreCase

您可以使用equalsIgnoreCase

回答by Gopi

More about string can be found in String Classand String Tutorials

有关字符串的更多信息可以在字符串类字符串教程中找到

回答by Aliti

You have to use the compareToIgnoreCasemethod of the Stringobject.

你必须使用对象的compareToIgnoreCase方法String

int compareValue = str1.compareToIgnoreCase(str2);

if (compareValue == 0)it means str1equals str2.

if (compareValue == 0)这意味着str1等于str2

回答by VeenarM

Note that you may want to do null checks on them as well prior to doing your .equals or .equalsIgnoreCase.

请注意,在执行 .equals 或 .equalsIgnoreCase 之前,您可能还想对它们进行空检查。

A null String object can not call an equals method.

null String 对象不能调用 equals 方法。

ie:

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);
}

回答by le-doude

In the default Java API you have:

在默认的 Java API 中,您有:

String.CASE_INSENSITIVE_ORDER

So you do not need to rewrite a comparator if you were to use strings with Sorted data structures.

因此,如果要使用带有 Sorted 数据结构的字符串,则无需重写比较器。

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":

只是为了进一步了解有关 Java 中字符串相等性的任何信息。java.lang.String 类的 hashCode() 函数“区分大小写”:

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 :

因此,如果您想使用以字符串作为键的 Hashtable/HashMap,并且将诸如“SomeKey”、“SOMEKEY”和“somekey”之类的键视为相等,那么您必须将字符串包装在另一个类中(您不能扩展字符串,因为它是最后一个类)。例如 :

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>();

回答by javacoder

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;
}

回答by KNU

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

现在它将输出: hai