Ho due Stringhe
, str1
e str2
. Come faccio a controllare se str2
è contenuto in str1
, ignorando il caso?
Puoi usare il metodo 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() )
}
Poi chiamatelo usando:
if( contains( str1, str2 ) ) {
System.out.println( "Found " + str2 + " within " + str1 + "." );
}
Notate che creando il vostro metodo, potete riutilizzarlo. Poi, quando qualcuno vi farà notare che dovreste usare contains
invece di indexOf
, avrete solo una singola linea di codice da cambiare.
Io userei una combinazione del metodo contains e del metodo toUpper
che fanno parte della classe String. Un esempio è qui sotto:
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()));
Questo restituirà:
Search1=true
Ricerca2=falso