Mam dwa String
, str1
i str2
. Jak mogę sprawdzić czy str2
jest zawarte wewnątrz str1
, ignorując przypadki?
Możesz użyć metody 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() )
}
Następnie wywołaj ją używając:
if( contains( str1, str2 ) ) {
System.out.println( "Found " + str2 + " within " + str1 + "." );
}
Zauważ, że tworząc własną metodę, możesz ją ponownie wykorzystać. Wtedy, gdy ktoś zwróci uwagę, że powinieneś użyć contains
zamiast indexOf
, masz tylko jedną linię kodu do zmiany.
I'd użyć kombinacji metody contains i metody toUpper
, które są częścią klasy String. Przykład jest poniżej:
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()));
Spowoduje to zwrócenie:
Search1=true
Search2=false