In Java, come si controlla se una stringa contiene una sottostringa (ignorando il caso)?

Ho due Stringhe, str1 e str2. Come faccio a controllare se str2 è contenuto in str1, ignorando il caso?

Soluzione
str1.toLowerCase().contains(str2.toLowerCase())
Commentari (9)

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.

Commentari (2)

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

Commentari (2)