How to use `string.startsWith()` method ignoring the case?

后端 未结 8 639
暖寄归人
暖寄归人 2020-12-14 05:13

I want to use string.startsWith() method but ignoring the case.

Suppose I have String \"Session\" and I use startsWith on \"sE

相关标签:
8条回答
  • 2020-12-14 05:39

    try this,

    String session = "Session";
    if(session.toLowerCase().startsWith("sEsSi".toLowerCase()))
    
    0 讨论(0)
  • 2020-12-14 05:41

    You can always do

    "Session".toLowerCase().startsWith("sEsSi".toLowerCase());
    
    0 讨论(0)
  • 2020-12-14 05:44

    use starts with and toLowerCase together

    like this

    "Session".toLowerCase().startsWith("sEsSi".toLowerCase());
    
    0 讨论(0)
  • 2020-12-14 05:46

    I know I'm late, but what about using StringUtils.startsWithIgnoreCase() from Apache Commons Lang 3 ?

    Example :

    StringUtils.startsWithIgnoreCase(string, "start");
    

    Just add the following dependency to your pom.xml file (taking the hypothesis that you use Maven) :

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.11</version>
    </dependency>
    
    0 讨论(0)
  • 2020-12-14 05:47

    One option is to convert both of them to either lowercase or uppercase:

    "Session".toLowerCase().startsWith("sEsSi".toLowerCase());
    

    This is wrong. See: https://stackoverflow.com/a/15518878/14731


    Another option is to use String#regionMatches() method, which takes a boolean argument stating whether to do case-sensitive matching or not. You can use it like this:

    String haystack = "Session";
    String needle = "sEsSi";
    System.out.println(haystack.regionMatches(true, 0, needle, 0, 5));  // true
    

    It checks whether the region of needle from index 0 till length 5 is present in haystack starting from index 0 till length 5 or not. The first argument is true, means it will do case-insensitive matching.


    And if only you are a big fan of Regex, you can do something like this:

    System.out.println(haystack.matches("(?i)" + Pattern.quote(needle) + ".*"));
    

    (?i) embedded flag is for ignore case matching.

    0 讨论(0)
  • 2020-12-14 05:51

    You can use someString.toUpperCase().startsWith(someOtherString.toUpperCase())

    0 讨论(0)
提交回复
热议问题