How to check if a String contains another String in a case insensitive manner in Java?

前端 未结 19 1647
渐次进展
渐次进展 2020-11-22 03:20

Say I have two strings,

String s1 = \"AbBaCca\";
String s2 = \"bac\";

I want to perform a check returning that s2 is contained

19条回答
  •  耶瑟儿~
    2020-11-22 04:03

    I did a test finding a case-insensitive match of a string. I have a Vector of 150,000 objects all with a String as one field and wanted to find the subset which matched a string. I tried three methods:

    1. Convert all to lower case

      for (SongInformation song: songs) {
          if (song.artist.toLowerCase().indexOf(pattern.toLowercase() > -1) {
                  ...
          }
      }
      
    2. Use the String matches() method

      for (SongInformation song: songs) {
          if (song.artist.matches("(?i).*" + pattern + ".*")) {
          ...
          }
      }
      
    3. Use regular expressions

      Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
      Matcher m = p.matcher("");
      for (SongInformation song: songs) {
          m.reset(song.artist);
          if (m.find()) {
          ...
          }
      }
      

    Timing results are:

    • No attempted match: 20 msecs

    • To lower match: 182 msecs

    • String matches: 278 msecs

    • Regular expression: 65 msecs

    The regular expression looks to be the fastest for this use case.

提交回复
热议问题