判斷字符串是否以特定前綴/後綴開頭結尾是常見需求。本文展示三種思路:標準 API、索引查找、子串截取,並附帶完整可運行代碼與運行結果截圖說明。
輸入字符串,判斷是否以 "ab" 開頭並以 "ab" 結尾。
Scanner sc = new Scanner(System.in);
String str = sc.next();
if (str.startsWith("ab")) System.out.print("以ab開頭,");
else System.out.print("不以ab開頭,");
if (str.endsWith("ab")) System.out.println("以ab結尾。");
else System.out.println("不以ab結尾。");
int first = str.indexOf("ab");
int last = str.lastIndexOf("ab");
if (first == 0 && last == str.length() - 2)
System.out.println("既以ab開頭又以ab結尾");
else if (first == 0)
System.out.println("僅以ab開頭");
else if (last == str.length() - 2)
System.out.println("僅以ab結尾");
else
System.out.println("均不符合");
String head = str.substring(0, 2);
String tail = str.substring(str.length() - 2);
if (head.equals("ab")) System.out.print("以ab開頭,");
else System.out.print("不以ab開頭,");
if (tail.equals("ab")) System.out.println("以ab結尾。");
else System.out.println("不以ab結尾。");

startsWith/endsWith:語義清晰、性能優化、可讀性最強