Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string at a certain position contains character a-h?

Tags:

I know there must be a simpler way to check, but this is what I'm doing right now.

if (g.charAt(0) == 'a' || g.charAt(0) =='b' || g.charAt(0) =='c' ||
    g.charAt(0) == 'd' || g.charAt(0) =='e' || g.charAt(0) =='f' ||
    g.charAt(0) == 'g' || g.charAt(0) =='h')
like image 604
ToonLink Avatar asked Feb 05 '14 20:02

ToonLink


People also ask

How do I find a character in a specific position in a string?

charAt(int position) method of String Class can be used to get the character at specific position in a String. Return type of charAt(int position) is char. Index or position is counted from 0 to length-1 characters.

How do I find a character in a certain position in a string Java?

Java String indexOf() Method The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.

How do you check if a character appears in a string?

You can use string. indexOf('a') . If the char a is present in string : it returns the the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.

How do you check if a string contains a specific substring?

You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.


2 Answers

Relying on character ordering and that a..h is a consecutive range:

char firstChar = g.charAt(0);
if (firstChar >= 'a' && firstChar <= 'h') {
   // ..
}
like image 134
user2864740 Avatar answered Sep 28 '22 11:09

user2864740


Use a regular expression for this one. Cut the first character of your String as a substring, and match on it.

if(g.substring(0, 1).matches("[a-h]") {
    // logic
}
like image 20
Makoto Avatar answered Sep 28 '22 11:09

Makoto