0

So I am trying to add alphabets or numbers into a list of characters? I do not want to have any spaces or . or , or ? or any other sign. I just want pure numbers and alphabets. Part of my code is as follows:

while((r = br.read()) != -1){
    char c = (char) r;
    if (!((c == ' ') || (c == ',') || (c == '.') || (c == '?')))
        output.add(c);
}

You can see I have added an if statement which checks for spaces or , or . or ? Is there any efficient way to do this? So that I do not have to include all the signs in the statement, hence, making it longer.

dimo414
  • 47,227
  • 18
  • 148
  • 244
Haris Ghauri
  • 547
  • 2
  • 7
  • 27
  • There are a whole load of `Character.is*` methods - perhaps `Character.isAlphabetic` and `isDigit` are what you are looking for. – Andy Turner Jul 20 '15 at 05:07
  • You can create a regex for this which will reduce complexity of your code. – Gaurav Jeswani Jul 20 '15 at 05:09
  • You could test against ascii range of digits and a-z| A-Z letters. This way you will filter everything that is not digit or letter. – John Jul 20 '15 at 05:12

3 Answers3

3

If you're checking it character-by-character, it'd be easy to check what is allowed, rather than what is not, especially since your criteria are just three ranges: 0-9, a-z and A-Z. For example:

if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
   output.add(c);
}

As you can see, it's not the prettiest code, which is why it'd be better to use Java's built-in Character.is? methods:

if (Character.isDigit(c) || Character.isLetter(c)) {
    output.add(c);
}

If however you are able to read strings, you can check their validity using regex, as such:

if (s.matches("[0-9A-Za-z]*")) {
    output.add(s);
}

This will only add the string if it contains zero or more digits and lowercase or uppercase letters, in any sequence. You can, of course, use it this solution for a one-character string, though it's less preferred (for characters, you'd be better off with the Character class).

Ori Lentz
  • 3,668
  • 6
  • 22
  • 28
2

Try this

if (Pattern.compile("[A-Za-z0-9]").matcher(String.valueOf(c)).matches()) {
    output.add(c);
}
SeniorJD
  • 6,946
  • 4
  • 36
  • 53
Ajmal Muhammad
  • 685
  • 7
  • 25
1

Try this:

while((r = br.read()) != -1){
     char c = (char) r;
     if (Character.isDigit(c) || Character.isLetter(c)) { 
         output.add(c);
     }
}

You can refer this link How to check if a character in a string is a digit or letter

Community
  • 1
  • 1
Vishnu
  • 375
  • 4
  • 16