字符串操作是業務開發高頻基礎。本文提供四個經典練習:Java 文件名後綴驗證、郵箱格式簡易校驗、指定字符出現次數統計、字符串中大小寫字母與其他字符分類計數,附帶完整代碼與運行結果分析。
.java 結尾,且 . 不能位於首位。@,且 @ 在 . 之前。public class StringValidationDemo {
public static void main(String[] args) {
String fileName = "HelloWorld.jav"; // 故意錯誤
String email = "user@example.com";
// 1. 文件名驗證
int dotIdx = fileName.lastIndexOf('.');
String suffix = (dotIdx > 0) ? fileName.substring(dotIdx) : "";
if (dotIdx > 0 && ".java".equals(suffix)) {
System.out.println("Java文件名正確");
} else {
System.out.println("Java文件名無效");
}
// 2. 郵箱驗證
int atIdx = email.indexOf('@');
int dotIdx2 = email.indexOf('.');
if (atIdx != -1 && dotIdx2 > atIdx) {
System.out.println("郵箱格式正確");
} else {
System.out.println("郵箱格式無效");
}
}
}
Java文件名無效
郵箱格式正確

統計字符串中字符 'a' 出現的次數。
public class CharCountDemo {
public static void main(String[] args) {
String s = "aljlkdsflkjsadjfklhasdkjlflkajdflwoiudsafhaasdasd";
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'a') count++;
}
System.out.println("字符 'a' 出現次數: " + count);
}
}
輸出字符串中大寫字母、小寫字母、其他字符的個數。
public class CharTypeCountDemo {
public static void main(String[] args) {
String s = "ABAabb$&^$#BAAb898B#@%aa";
int upper = 0, lower = 0, other = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c >= 'A' && c <= 'Z') upper++;
else if (c >= 'a' && c <= 'z') lower++;
else other++;
}
System.out.println("總長度: " + s.length());
System.out.println("大寫字母: " + upper);
System.out.println("小寫字母: " + lower);
System.out.println("其他字符: " + other);
}
}
總長度: 24
大寫字母: 7
小寫字母: 10
其他字符: 7

Pattern.compile(regex).matcher(email).matches(),支援 RFC 5322 完整規範。s.chars().filter(c -> c == 'a').count() 簡化統計。Character.isUpperCase(c)、isLowerCase(c)、isDigit(c) 替代手動範圍判斷,支援 Unicode。char[] 直接遍歷,避免 charAt 邊界檢查開銷。