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

发布于 2024-08-20 23:59:41 字数 217 浏览 1 评论 0原文

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

String str = "Hello";

if (str.equals("hello")) {
    System.out.println("match");
} else {
    System.out.println("no match");
}

它区分大小写。我怎样才能改变它,使它不再是这样?

I created a Java program to compare two strings:

String str = "Hello";

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

海拔太高太耀眼 2024-08-27 23:59:41

最好的方法是使用 str.equalsIgnoreCase("foo")。它专门为此目的进行了优化。

您还可以在与 equals 进行比较之前将这两个字符串转换为大写或小写。对于可能没有等价的 equalsIgnoreCase 的其他语言来说,记住这个技巧很有用。

str.toUpperCase().equals(str2.toUpperCase())

如果您使用非罗马字母,请注意 JavaDoc of equalsIgnoreCase 的这一部分,其中表示

请注意,此方法不考虑区域设置,并且会
导致某些区域设置的结果不令人满意
整理器
类提供区域设置敏感的比较。

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.

沧桑㈠ 2024-08-27 23:59:41

使用String.equalsIgnoreCase()

使用 Java API 参考来查找如下答案:

https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#equalsIgnoreCase(java.lang.String)

< a href="https://docs.oracle.com/javase/1.5.0/docs/api/" rel="noreferrer">https://docs.oracle.com/javase/1.5.0/docs/api /

云醉月微眠 2024-08-27 23:59:41

< code>String.equalsIgnoreCase 是简单的不区分大小写字符串比较的最实用选择。

不过,值得注意的是,此方法既不进行完整大小写折叠,也不进行分解,因此无法执行 Unicode 标准中指定的无大小写匹配。事实上,JDK API 不提供对有关大小写折叠字符数据的信息,因此这项工作最好委托给经过尝试和测试的第三方库。

该库是 ICU,以下是如何实现一个实用程序不区分大小写的字符串比较:

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

即使是这个简单的测试,在大写或小写字符串上与 String.equalsIgnoreCaseString.equals 进行简单比较也会失败。

(请注意,预定义的大小写折叠风格 getNFKCCasefoldInstance 与语言环境无关;对于土耳其语语言环境,需要更多工作,涉及 UCharacter.foldCase 可能是必要的。)

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.)

最近可好 2024-08-27 23:59:41

您必须使用 String 对象的 compareToIgnoreCase 方法。

int compareValue = str1.compareToIgnoreCase(str2);

if (compareValue == 0) 表示 str1 等于 str2

You have to use the compareToIgnoreCase method of the String object.

int compareValue = str1.compareToIgnoreCase(str2);

if (compareValue == 0) it means str1 equals str2.

溺ぐ爱和你が 2024-08-27 23:59:41
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");
}

现在它将输出:hai

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

小…楫夜泊 2024-08-27 23:59:41

在默认的 Java API 中,您有:

String.CASE_INSENSITIVE_ORDER

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

String s = "some text here";
s.equalsIgnoreCase("Some text here");

是您想要在自己的代码中进行纯粹的相等检查的内容。

只是为了进一步了解有关 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;
}

因此,如果您想使用以字符串作为键的 Hashtable/HashMap,并且具有像“SomeKey”、“SOMEKEY”和“somekey”这样的键,请执行以下操作:视为相等,那么您必须将字符串包装在另一个类中(您不能扩展 String,因为它是最终类)。例如:

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

然后这样使用它:

HashMap<HashWrap, Object> map = new HashMap<HashWrap, Object>();

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>();
黯然 2024-08-27 23:59:41

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

null String 对象无法调用 equals 方法。

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

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);
}
琴流音 2024-08-27 23:59:41

有关字符串的更多信息可以在 String Class< /a> 和 字符串教程

More about string can be found in String Class and String Tutorials

动次打次papapa 2024-08-27 23:59:41

为了空安全,您可以使用

org.apache.commons.lang.StringUtils.equalsIgnoreCase(String, String)

org.apache.commons.lang3.StringUtils.equalsIgnoreCase(CharSequence, CharSequence)

To be nullsafe, you can use

org.apache.commons.lang.StringUtils.equalsIgnoreCase(String, String)

or

org.apache.commons.lang3.StringUtils.equalsIgnoreCase(CharSequence, CharSequence)
不念旧人 2024-08-27 23:59:41
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;
}
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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文