java 如何在java中使indexof不区分大小写
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25943838/
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
how to make indexof case insensitive in java
提问by javalearner
I have a simple question. How do I make indexof case insensitive in java. This question has been already answered in some forum but I didn't understand the answer.
我有一个简单的问题。如何在 java 中使 indexof 不区分大小写。这个问题已经在一些论坛上得到了回答,但我不明白答案。
Say for eg.I have a string s = Phone(Conf) I want to pull the record that has (Conf) like this but the users are entering CONF or conf or Conf etc. So my program should be able to pull the record if it finds the word conf in any case.
比如说,我有一个字符串 s = Phone(Conf) 我想拉出这样的 (Conf) 记录,但用户正在输入 CONF 或 conf 或 Conf 等。所以我的程序应该能够提取记录,如果它在任何情况下都会找到单词 conf。
if(s.indexOf("(")>-1&& s.indexOf("Conf")>-4 && s.lastIndexOf(")")>-1)
{
String s1=s.substring(s.indexOf("(Conf"),s.lastIndexOf(")")+1);
}
can someone explain me pls? The above code pulls it if the string is (Conf) only.
有人可以解释一下吗?如果字符串是 (Conf) only,上面的代码会拉它。
回答by Crenguta S
The safest way to do it would be:
最安全的方法是:
content.toLowerCase().indexOf(searchTerm.toLowerCase())
, this way you cover 2 possible edge cases when the content may be in lower case and the search term would be in upper case or both would be upper case.
content.toLowerCase().indexOf(searchTerm.toLowerCase())
,这样您就可以涵盖 2 种可能的边缘情况,当内容可能是小写而搜索词可能是大写或两者都是大写时。
回答by Eng.Fouad
One common solution:
一种常见的解决方案:
yourString.toLowerCase().indexOf("foo");