简体   繁体   English

检查字符串是否由 3 个大写字母和 4 个数字组成(在 JAVA 中)

[英]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.我需要检查一个字符串是否由 3 个大写字母和 4 个数字组成。

For example: ABC1234例如:ABC1234

OBS: Without using regular expressions? OBS:不使用正则表达式?

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"); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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