2

I am was making an if statement when I needed to check whether an unknown char is of any character set. Predefined or Custom.

I could just make many or statements but it would get messy. So is there any regex present to do this. I used a charAt(); function to get the last digit of it.I needed to check whether it is a digit or not. I currently need for digits only(0-9) but I would need more too.

This is my IF Statement

.....
if(mytext.equals("(") && (mytext2.charAt(text.length()-1)=='') {
......
}
.......

Please Help

  • 1
    `"setofchars".indexOf(unknownChar) >= 0`. – Andy Turner Jun 08 '19 at 08:04
  • I appreciate the quick accept, but sorry, I do not understand your follow on question in the comment. You asked how to determine if a given character is in some set of chars. If you have a new question how to input characters, well, then consider asking a new question. – GhostCat Jun 08 '19 at 10:19
  • Look at the name of the variable that receives the result of that expression. It is called *validCharacters*. It is not called "inputFromUser*. Also note that nothing in that line could come from a user running the code. All the information there is already present in the source code. The idea is that *unknownCharacter* is a value that the user somehow provided at run time. – GhostCat Jun 09 '19 at 04:48
  • Please use @ username when replying to comments. That was just an example, yes, the idea would be that you write down the valid characters as argument to asList(). But note: when you want digits only there are helper methods, like Character.isDigit() that you can use instead. – GhostCat Jun 09 '19 at 10:05
  • You are welcome. Please consider to now delete all comments that are no longer required. We like to keep things tidy here :-) – GhostCat Jun 10 '19 at 06:55

2 Answers2

2

You can use the Set interface like:

Set<Character> validChars = new HashSet<>(Arrays.asList('a', 'X, '1'));
if (validChars.contains(unknownChar)) {
  ...

for example. That gives you theoretically the best performance, although that won't matter much here.

Alternatively, you can collect your valid chars in a "string", as indicated by the comment. You then use thatString.indexOf(unknownChar), and if the method does return an index equal/greater than 0, you know "it is valid", too.

The third option would be to look into regular expressions, but for a newbie, I suggest either option 1 or 2.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
1

By using contains method

"SetOfCharacters".contains("a")

if it returns true then SetOfCharacters contain a

You can use it for any character,whether its a digit or any other special character.

NullByte08
  • 884
  • 10
  • 15