由用戶隨機輸入一個字符串 判斷是否以指定的字符開頭 並以指定的字符結束:
1 // 隨機輸入一個字符串 判斷是否以ab開頭 以ab結束
2 Scanner sc = new Scanner(System.in);
3 System.out.println("請輸入一個字符串:");
4 String str = sc.next();
5 // 類查詢
6 if (str.startsWith("ab")) {
7 System.out.print("字符串以ab開頭,");
8 } else {
9 System.out.print("字符串不是以ab開頭,");
10 }
11 if (str.endsWith("ab")) {
12 System.out.println("以ab結束。");
13 } else {
14 System.out.println("不是以ab結束。");
15 }
16 // 索引查詢
17 int num1, num2;
18 num1 = str.indexOf("ab");
19 num2 = str.lastIndexOf("ab");
20 if (num1 == 0 && num2 == str.length() - 2) {
21 System.out.println("這個字符串是以ab開頭並且以ab結束。");
22 } else if (num1 == 0 && num2 != str.length() - 2) {
23 System.out.println("這個字符串只是以ab開頭,");
24
25 } else if (num1 != 0 && num2 == str.length() - 2) {
26 System.out.println("這個字符串只是以ab結束。");
27 } else {
28 System.out.println("這個字符串既不以ab開頭,又不以ab結束。");
29 }
30
31 // 截取字符串查詢
32 String str1 = str.substring(0, 2);
33 String str2 = str.substring(str.length() - 2, str.length());
34 if (str1.equals("ab")) {
35 System.out.print("字符串以ab開頭,");
36 } else {
37 System.out.print("字符串不是以ab開頭,");
38 }
39 if (str2.equals("ab")) {
40 System.out.println("以ab結束。");
41 } else {
42 System.out.println("不是以ab結束。");
43 }
運行結果:

