在給定的字元串中查找字元或字元串是比較常見的操作。字元串查找分為兩種形式:一種是在字元串中擷取比對字元(串)的索引值,另一種是在字元串中擷取指定索引位置的字元。
根據字元查找
String 類的 indexOf() 方法和 lastlndexOf() 方法用于在字元串中擷取比對字元(串)的索引值。
1. indexOf() 方法
indexOf() 方法用于傳回字元(串)在指定字元串中首次出現的索引位置,如果能找到,則傳回索引值,否則傳回 -1。該方法主要有兩種重載形式:
str.indexOf(value)
str.indexOf(value,int fromIndex)
其中,str 表示指定字元串;value 表示待查找的字元(串);fromIndex 表示查找時的起始索引,如果不指定 fromIndex,則預設從指定字元串中的開始位置(即 fromIndex 預設為 0)開始查找。
例如,下列代碼在字元串“Hello Java”中查找字母 v 的索引位置。
String s = "Hello Java";
int size = s.indexOf('v'); // size的結果為8
上述代碼執行後 size 的結果為 8,它的查找過程如圖 1 所示。
圖1 indexOf() 方法查找字元過程
例 1
編寫一個簡單的 Java 程式,示範 indexOf() 方法查找字元串的用法,并輸出結果。代碼如下:
public static void main(String[] args) {
String words = "today,monday,sunday";
System.out.println("原始字元串是'"+words+"'");
System.out.println("indexOf(\"day\")結果:"+words.indexOf("day"));
System.out.println("indexOf(\"day\",5)結果:"+words.indexOf("day",5));
System.out.println("indexOf(\"o\")結果:"+words.indexOf("o"));
System.out.println("indexOf(\"o\",6)結果:"+words.indexOf("o",6));
}
運作後的輸出結果如下:
原始字元串是'today,monday,sunday'
indexOf("day")結果:2
indexOf("day",5)結果:9
indexOf("o")結果:1
indexOf("o",6)結果:7
2. lastlndexOf() 方法
lastIndexOf() 方法用于傳回字元(串)在指定字元串中最後一次出現的索引位置,如果能找到則傳回索引值,否則傳回 -1。該方法也有兩種重載形式:
str.lastIndexOf(value)
str.lastlndexOf(value, int fromIndex)
注意:lastIndexOf() 方法的查找政策是從右往左查找,如果不指定起始索引,則預設從字元串的末尾開始查找。
例 2
編寫一個簡單的 Java 程式,示範 lastIndexOf() 方法查找字元串的用法,并輸出結果。代碼如下:
public static void main(String[] args) {
String words="today,monday,Sunday";
System.out.println("原始字元串是'"+words+"'");
System.out.println("lastIndexOf(\"day\")結果:"+words.lastIndexOf("day"));
System.out.println("lastIndexOf(\"day\",5)結果:"+words.lastIndexOf("day",5));
System.out.println("lastIndexOf(\"o\")結果:"+words.lastIndexOf("o"));
System.out.println("lastlndexOf(\"o\",6)結果:"+words.lastIndexOf("o",6));
}
運作後的輸出結果如下:
原始字元串是'today,monday,Sunday'
lastIndexOf("day")結果:16
lastIndexOf("day",5)結果:2
lastIndexOf("o")結果:7
lastlndexOf("o",6)結果:1
根據索引查找
String 類的 charAt() 方法可以在字元串内根據指定的索引查找字元,該方法的文法形式如下:
字元串名.charAt(索引值)
提示:字元串本質上是字元數組,是以它也有索引,索引從零開始。
charAt() 方法的使用示例如下:
String words = "today,monday,sunday";
System.out.println(words.charAt(0)); // 結果:t
System.out.println(words.charAt(1)); // 結果:o
System.out.println(words.charAt(8)); // 結果:n