[英]Checking if a string is composed of 3 capital letters and 4 numbers (in JAVA)
我需要檢查一個字符串是否由 3 個大寫字母和 4 個數字組成。
例如:ABC1234
OBS:不使用正則表達式?
這是我到目前為止所嘗試的。 謝謝!
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);
}
我猜字母和數字在字符串中的隨機位置。
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.