我有两个 "字符串",str1和str2。我如何检查str2是否包含在str1中,忽略大小写?
str1
str2
str1.toLowerCase().contains(str2.toLowerCase())
你可以使用toLowerCase()方法。
toLowerCase()
public boolean contains( String haystack, String needle ) { haystack = haystack == null ? "" : haystack; needle = needle == null ? "" : needle; // Works, but is not the best. //return haystack.toLowerCase().indexOf( needle.toLowerCase() ) > -1 return haystack.toLowerCase().contains( needle.toLowerCase() ) }
然后用以下方法来调用它。
if( contains( str1, str2 ) ) { System.out.println( "Found " + str2 + " within " + str1 + "." ); }
注意,通过创建你自己的方法,你可以重复使用它。然后,当有人指出你应该使用contains而不是indexOf时,你只需要修改一行代码。
contains
indexOf
我将使用包含方法和toUpper方法的组合,这是字符串类的一部分。 下面是一个例子。
toUpper
String string1 = "AAABBBCCC"; String string2 = "DDDEEEFFF"; String searchForThis = "AABB"; System.out.println("Search1="+string1.toUpperCase().contains(searchForThis.toUpperCase())); System.out.println("Search2="+string2.toUpperCase().contains(searchForThis.toUpperCase()));
这将返回。
Search1=true 搜索2=false
你可以使用
toLowerCase()
方法。然后用以下方法来调用它。
注意,通过创建你自己的方法,你可以重复使用它。然后,当有人指出你应该使用
contains
而不是indexOf
时,你只需要修改一行代码。我将使用包含方法和
toUpper
方法的组合,这是字符串类的一部分。 下面是一个例子。这将返回。