本文继续演示String方法。
² charAt()返回指字索引位置的字符。
² indexOf()是返回指定的子串在字符串出现的位置,若不存在则返回-1。
² lastIndexOf()返回指定的子串大字符串从后开始出现的位置,若不存在则返回-1。
² contains() 测试是否包含指定的子串。
示例2:演示charAt(),indexOf,lastIndexOf,contains方法。
package string.lang.java;
public class StringDemo3 {
public static void main(String[] args) { String str = "abc123abc"; // 获得索引值为1的字符 char ch = str.charAt(1); System.out.println("索引值为1的字符是:" + ch); // 求子串 String str1 = str.substring(3, 6); System.out.println("从索引3开始至索引6(不含)的子串为:" + str1); String str2 = str.substring(3); System.out.println("从索引3开始至未尾的子串为:" + str2); // 求子串在字符串出现的位置 int index1 = str.indexOf("abc"); System.out.println("子串abc首次出现的位置是:" + index1); int index2 = str.indexOf("abc", 2); System.out.println("子串abc在索引2开始出现的位置是:" + index2);
// 求子串在字符串出现的位置(从后开始) int index3 = str.lastIndexOf("abc"); System.out.println("子串abc最后次出现的位置是:" + index3);
// 方式一:测试是否包含指定的子串 int index4 = str.indexOf("ABC"); if (index4 == -1) { System.out.println("子串ABC不存在"); } else { System.out.println("子串ABC出现的位置是:" + index4); } // 方式一: 测试是否包含指定的子串 boolean flag = str.contains("abc"); if (flag) { System.out.println("包含"); } else { System.out.println("不包含"); }
}
}
|
运行的结果如下: