String类提供了两种查找字符串的方法,即indexOf(与lastIndexOf0方法。这两种方法都允许在字符串中搜索指定条件的字符或字符串。indexOf(方法返回的是搜索的字符或字符串首次出现的位置,lastIndexOf0方法返回的是搜索的字符或字符串最后-次出现的位置。 (1) indexOf(String s) 该方法用于返回参数字符串s在指定字符串中首次出现的索引位置。当调用字符串的indexOf(方法时,会从当前字符串的开始位置搜索s的位置;如果没有检索到字符串s,该方法的返回值是-1。 2) lastIndexOf(String str) 该方法用于返回指定字符串最后-次出现的索引位置。当调用字符串的lastIndexOf(方法时,会从当前字符串的开始位置检索参数字符串str,并将最后一次出现str的索引位置返回。如果没有检索到字符串str,该方法返回-1。 语法如下: str. lastlndexOf(substr) str:任意字符串对象。 substr:要搜索的字符串。
3.使用charAt0方法可将指定索引处的字符返回。语法如下: str.charAt(int index)
举例:
package test; public class Three { public static void main(String[] args) { // TODO 自动生成的方法存根 String s="Hello word"; int size=s.indexOf("l"); System.out.println("l:第一次出现在第"+size+"个位置; "+"总长度为"+s.length()); char c=s.charAt(size); System.out.println(size+":位置的字符为"+c); int size2=s.lastIndexOf("o"); System.out.println("0最后出现在第"+size2+"个位置"+"总长度为"+s.length()); char c2=s.charAt(size2); System.out.println(size2+":位置的字符为"+c2); } }结果: