Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check string format without using regular expressions?

Tags:

java

I'm working on a project where I need to check if a string is in the correct format ABC1234 meaning 3 letters followed by 4 numbers. I was told not to use regular expressions to solve this.

I came up with the following code but it's clunky so I'm looking for something cleaner and more efficient.

String sample = ABC1234

char[] chars = sample.toCharArray();

if(Character.isLetter(chars[0]) && Character.isLetter(chars[1]) && 
   Character.isLetter(chars[2]) && Character.isDigit(chars[3]) && 
   Character.isDigit(chars[4]) && Character.isDigit(chars[5]) && 
   Character.isDigit(chars[6])){

    list.add(sample);
}

// OUTPUT: ABC1234 gets added to "list". When it prints, it appears as ABC1234.

All outputs are as expected but I know this can be done either more efficiently or just better in general.

I'm just checking the first 3 chars to verify they're each a letter and the last 4 chars should be numbers.

Any advice? Thanks in advance.

like image 979
Carlos De la Torre Avatar asked Mar 04 '23 20:03

Carlos De la Torre


1 Answers

You do not need

char[] chars = sample.toCharArray();

Instead you can just do

if(Character.isLetter(sample.charAt(0))

You can also be more fancy and do something like :

void myFonc(string sample) {
 for (int i =0; i < 3; ++i)
        if (!Character.isLetter(sample.charAt(i)))
            return;

 for (int i =3; i < 7; ++i)
        if (!Character.isDigit(sample.charAt(i)))
            return;
list.add(sample);

}
like image 65
YouneS Avatar answered Mar 16 '23 17:03

YouneS