建設(shè)網(wǎng)站合同最新重大新聞
在給定的字符串中查找字符或字符串是比較常見(jiàn)的操作。字符串查找分為兩種形式:一種是在字符串中獲取匹配字符(串)的索引值,另一種是在字符串中獲取指定索引位置的字符。
根據(jù)字符查找
String 類的 indexOf() 方法和 lastlndexOf() 方法用于在字符串中獲取匹配字符(串)的索引值。
1. indexOf() 方法
indexOf() 方法用于返回字符(串)在指定字符串中首次出現(xiàn)的索引位置,如果能找到,則返回索引值,否則返回 -1。該方法主要有兩種重載形式:
- str.indexOf(value)
- str.indexOf(value,int fromIndex)
其中,str 表示指定字符串;
value 表示待查找的字符(串);
fromIndex 表示查找時(shí)的起始索引,如果不指定 fromIndex,則默認(rèn)從指定字符串中的開(kāi)始位置(即 fromIndex 默認(rèn)為 0)開(kāi)始查找。
例如,下列代碼在字符串“Hello Java”中查找字母 v 的索引位置。
String s = "Hello Java";
int size = s.indexOf('v'); // size的結(jié)果為8
上述代碼執(zhí)行后 size 的結(jié)果為 8,它的查找過(guò)程如圖 1 所示。
例 1
編寫(xiě)一個(gè)簡(jiǎn)單的 Java 程序,演示 indexOf() 方法查找字符串的用法,并輸出結(jié)果。代碼如下:
public static void main(String[] args) {String words = "today,monday,sunday";System.out.println("原始字符串是'"+words+"'");System.out.println("indexOf(\"day\")結(jié)果:"+words.indexOf("day"));System.out.println("indexOf(\"day\",5)結(jié)果:"+words.indexOf("day",5));System.out.println("indexOf(\"o\")結(jié)果:"+words.indexOf("o"));System.out.println("indexOf(\"o\",6)結(jié)果:"+words.indexOf("o",6));
}
運(yùn)行后的輸出結(jié)果如下:
原始字符串是'today,monday,sunday'
indexOf("day")結(jié)果:2
indexOf("day",5)結(jié)果:9
indexOf("o")結(jié)果:1
indexOf("o",6)結(jié)果:7
2. lastlndexOf() 方法
lastIndexOf() 方法用于返回字符(串)在指定字符串中最后一次
出現(xiàn)的索引位置,如果能找到則返回索引值,否則返回 -1。該方法也有兩種重載形式:
- str.lastIndexOf(value)
- str.lastlndexOf(value, int fromIndex)
注意:lastIndexOf() 方法的查找策略是從右往左查找,如果不指定起始索引,則默認(rèn)從字符串的末尾開(kāi)始查找
。
例 2
編寫(xiě)一個(gè)簡(jiǎn)單的 Java 程序,演示 lastIndexOf() 方法查找字符串的用法,并輸出結(jié)果。代碼如下:
public static void main(String[] args) {String words="today,monday,Sunday";System.out.println("原始字符串是'"+words+"'");System.out.println("lastIndexOf(\"day\")結(jié)果:"+words.lastIndexOf("day"));System.out.println("lastIndexOf(\"day\",5)結(jié)果:"+words.lastIndexOf("day",5));System.out.println("lastIndexOf(\"o\")結(jié)果:"+words.lastIndexOf("o"));System.out.println("lastlndexOf(\"o\",6)結(jié)果:"+words.lastIndexOf("o",6));
}
運(yùn)行后的輸出結(jié)果如下:
原始字符串是'today,monday,Sunday'
lastIndexOf("day")結(jié)果:16
lastIndexOf("day",5)結(jié)果:2
lastIndexOf("o")結(jié)果:7
lastlndexOf("o",6)結(jié)果:1
根據(jù)索引查找
String 類的 charAt() 方法可以在字符串內(nèi)根據(jù)指定的索引查找字符,該方法的語(yǔ)法形式如下:
字符串名.charAt(索引值)
提示:字符串本質(zhì)上是字符數(shù)組,因此它也有索引,索引從零開(kāi)始
。
charAt() 方法的使用示例如下:
String words = "today,monday,sunday";
System.out.println(words.charAt(0)); // 結(jié)果:t
System.out.println(words.charAt(1)); // 結(jié)果:o
System.out.println(words.charAt(8)); // 結(jié)果:n