Determine if string starts with letters A through I

前端 未结 6 730
北海茫月
北海茫月 2021-01-11 15:30

I\'ve got a simple java assignment. I need to determine if a string starts with the letter A through I. I know i have to use string.startsWith(); but I don\'t want to write,

相关标签:
6条回答
  • 2021-01-11 16:07

    How about this for brevity?

    if (0 <= "ABCDEFGHI".indexOf(string.charAt(0))) {
        // string starts with a character between 'A' and 'I' inclusive
    }
    
    0 讨论(0)
  • 2021-01-11 16:19

    Try

    string.charAt(0) >= 'a' && string.charAt(0) <= 'j'
    
    0 讨论(0)
  • 2021-01-11 16:22

    You don't need regular expressions for this.

    Try this, assuming you want uppercase only:

    char c = string.charAt(0);
    if (c >= 'A' && c <= 'I') { ... }
    

    If you do want a regex solution however, you can use this (ideone):

    if (string.matches("^[A-I].*$")) { ... }
    
    0 讨论(0)
  • 2021-01-11 16:27
    if ( string.charAt(0) >= 'A' && string.charAt(0) <= 'I' )
    {
    }
    

    should do it

    0 讨论(0)
  • 2021-01-11 16:30
    char c=string.toLowerCase().charAt(0);
    if( c >= 'a' && c <= 'i' )
        ...
    

    This makes it easy to extract it as a method:

    public static boolean startsBetween(String s, char lowest, char highest) {
        char c=s.charAt(0);
        c=Character.toLowerCase(c);  //thx refp
        return c >= lowest && c <= highest;
    }
    

    which is HIGHLY preferred to any inline solution. For the win, tag it as final so java inlines it for you and gives you better performance than a coded-inline solution as well.

    0 讨论(0)
  • 2021-01-11 16:33

    if ( string.toUpperCase().charAt(0) >= 'A' && string.toUpperCase().charAt(0) <= 'I' )

    should be the easiest version...

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