Ako v jazyku Java skontrolujem, či reťazec obsahuje podreťazec (bez ohľadu na veľkosť písmen)?

Mám dva reťazce, str1 a str2. Ako môžem skontrolovať, či je str2 obsiahnutý v str1, pričom ignorujem veľkosť písmen?

Riešenie
str1.toLowerCase().contains(str2.toLowerCase())
Komentáre (9)

Môžete použiť metódu 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() )
}

Potom ju zavolajte pomocou:

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

Všimnite si, že vytvorením vlastnej metódy ju môžete použiť opakovane. Keď vás potom niekto upozorní, že namiesto metódy indexOf by ste mali použiť metódu contains, budete musieť zmeniť len jeden riadok kódu.

Komentáre (2)

Použil by som kombináciu metódy contains a metódy toUpper, ktoré sú súčasťou triedy String. Príklad je uvedený nižšie:

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

Toto vráti:

Search1=true
Search2=false

Komentáre (2)