En Java, comment vérifier si une chaîne de caractères contient une sous-chaîne (en ignorant la casse) ?

J'ai deux Strings, str1 et str2. Comment puis-je vérifier si str2 est contenue dans str1, en ignorant la casse ?

Solution
str1.toLowerCase().contains(str2.toLowerCase())
Commentaires (9)

Vous pouvez utiliser la méthode 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() )
}

Puis l'appeler en utilisant :

if( contains( str1, str2 ) ) {
  System.out.println( "Found " + str2 + " within " + str1 + "." );
}

Remarquez qu'en créant votre propre méthode, vous pouvez la réutiliser. Ainsi, lorsque quelqu'un vous fera remarquer que vous devriez utiliser contains au lieu de indexOf, vous n'aurez qu'une seule ligne de code à modifier.

Commentaires (2)

J'utiliserais une combinaison de la méthode contains et de la méthode toUpper qui font partie de la classe String. Voici un exemple :

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()));

Ceci retournera :

Search1=true
Search2=false

Commentaires (2)