如何使我的字符串比较不区分大小写? [英] How do I make my string comparison case-insensitive?

查看:35
本文介绍了如何使我的字符串比较不区分大小写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

The best way is to use str.equalsIgnoreCase("foo"). It's optimized specifically for this purpose.

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

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

如果您使用的是非罗马字母,请注意 equalsIgnoreCase 的 JavaDoc 的这一部分

If you are using a non-Roman alphabet, take note of this part of the JavaDoc of equalsIgnoreCase which says

请注意,此方法不考虑区域设置,并且会导致某些地区的结果不令人满意.Collat​​or类提供区域敏感的比较.

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.

这篇关于如何使我的字符串比较不区分大小写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆