簡體   English   中英

檢查字符串是否由 3 個大寫字母和 4 個數字組成(在 JAVA 中)

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM