indexOf Case Sensitive?

后端 未结 19 1285
日久生厌
日久生厌 2020-11-27 19:39

Is the indexOf(String) method case sensitive? If so, is there a case insensitive version of it?

19条回答
  •  猫巷女王i
    2020-11-27 19:58

    Yes, it is case-sensitive. You can do a case-insensitive indexOf by converting your String and the String parameter both to upper-case before searching.

    String str = "Hello world";
    String search = "hello";
    str.toUpperCase().indexOf(search.toUpperCase());
    

    Note that toUpperCase may not work in some circumstances. For instance this:

    String str = "Feldbergstraße 23, Mainz";
    String find = "mainz";
    int idxU = str.toUpperCase().indexOf (find.toUpperCase ());
    int idxL = str.toLowerCase().indexOf (find.toLowerCase ());
    

    idxU will be 20, which is wrong! idxL will be 19, which is correct. What's causing the problem is tha toUpperCase() converts the "ß" character into TWO characters, "SS" and this throws the index off.

    Consequently, always stick with toLowerCase()

提交回复
热议问题