简体   繁体   中英

Checking if a string is composed of 3 capital letters and 4 numbers (in JAVA)

I need to check if a string is composed by 3 capital letters and 4 digits.

For example: ABC1234

OBS: Without using regular expressions?

This is what I have tried so far. Thanks!

public static void main(String[] args) {
String input  = "ABC1234"; 
String firstThreeChars = ""; //substring containing first three characters
String lastFourChars = ""; //substring containing last four characters

if (input.length() > 4) {
  firstThreeChars = input.substring(0, 3);
}

if (input.length() > 4) {
  lastFourChars = input.substring(input.length() - 4);
}

System.out.println(firstThreeChars);
System.out.println(lastFourChars);

}

I'm guessing that the letters and numbers are in random places in the string.


Just use two counters and count.

 if (input.length != 7) { System.out.println("No"); return; } int letterCount = 0, digitCount = 0; for (int i = 0; i < 7; ++i) { char c = input.charAt(i); if (c >= 'A' && c <= 'Z') { ++letterCount; } else if (c >= '0' && c <= '9') { ++digitCount; } else { System.out.println("No"); return; } } if (letterCount == 3 && digitCount == 4) { System.out.println("Yes"); } else { System.out.println("No"); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM