Java 如何使用`string.startsWith()` 方法忽略大小写?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19154117/
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-12 14:34:05  来源:igfitidea点击:

How to use `string.startsWith()` method ignoring the case?

javastring

提问by Sheetal Bhatewara

I want to use string.startsWith()method but ignoring the case.

我想使用string.startsWith()方法但忽略大小写。

Suppose I have String"Session" and I use startsWithon "sEsSi" then it should return true.

假设我有String“Session”并且我startsWith在“sEsSi”上使用,那么它应该返回true.

How can I achieve this?

我怎样才能做到这一点?

采纳答案by Nemesis

Use toUpperCase()or toLowerCase()to standardise your string before testing it.

在测试之前使用toUpperCase()toLowerCase()来标准化您的字符串。

回答by Rohit Jain

One option is to convert both of them to either lowercase or uppercase:

一种选择是将它们都转换为小写或大写:

"Session".toLowerCase().startsWith("sEsSi".toLowerCase());
"Session".toLowerCase().startsWith("sEsSi".toLowerCase());

This is wrong. See: https://stackoverflow.com/a/15518878/14731

这是错误的。参见:https: //stackoverflow.com/a/15518878/14731



Another option is to use String#regionMatches()method, which takes a boolean argument stating whether to do case-sensitive matching or not. You can use it like this:

另一种选择是使用String#regionMatches()方法,它接受一个布尔参数,说明是否进行区分大小写的匹配。你可以这样使用它:

String haystack = "Session";
String needle = "sEsSi";
System.out.println(haystack.regionMatches(true, 0, needle, 0, 5));  // true

It checks whether the region of needlefrom index 0till length 5is present in haystackstarting from index 0till length 5or not. The first argument is true, means it will do case-insensitive matching.

它检查needle从索引0到长度的区域是否5存在于haystack从索引0到长度的开始5。第一个参数是true, 意味着它将进行不区分大小写的匹配。



And if only you are a big fan of Regex, you can do something like this:

如果您是Regex 的忠实粉丝,您可以执行以下操作:

System.out.println(haystack.matches("(?i)" + Pattern.quote(needle) + ".*"));

(?i)embedded flag is for ignore case matching.

(?i)嵌入标志用于忽略大小写匹配。

回答by agad

myString.toLowerCase().startsWith(starting.toLowerCase());

回答by newuser

try this,

尝试这个,

String session = "Session";
if(session.toLowerCase().startsWith("sEsSi".toLowerCase()))

回答by RamonBoza

You can always do

你总能做到

"Session".toLowerCase().startsWith("sEsSi".toLowerCase());

回答by Prasad Kharkar

You can use someString.toUpperCase().startsWith(someOtherString.toUpperCase())

您可以使用 someString.toUpperCase().startsWith(someOtherString.toUpperCase())

回答by rachit

use starts with and toLowerCase together

一起使用以和 toLowerCase 开头

like this

像这样

"Session".toLowerCase().startsWith("sEsSi".toLowerCase());