我們可以使用indexOf()和lastIndexOf()方法獲取另一個字符串中的字符或字符串的索引。例如
public class Main { public static void main(String[] args) { String str = new String("Apple"); int index = str.indexOf("p"); // index will have a value of 1 System.out.println(index); index = str.indexOf("pl"); // index will have a value of 2 System.out.println(index); index = str.lastIndexOf("p"); // index will have a value of 2 System.out.println(index); index = str.lastIndexOf("pl"); // index will have a value of 2 System.out.println(index); index = str.indexOf("k"); // index will have a value of -1 System.out.println(index); } }
上面的代碼生成以下結(jié)果。
indexOf()方法從字符串的開頭開始搜索字符或字符串,并返回第一個匹配的索引。
lastIndexOf()方法從末尾匹配字符或字符串,并返回第一個匹配的索引。
如果在字符串中沒有找到字符或字符串,這些方法返回-1。
startsWith()檢查字符串是否以指定的參數(shù)開頭,而endsWith()檢查字符串是否以指定的字符串參數(shù)結(jié)尾。
兩個方法都返回一個布爾值。
public class Main { public static void main(String[] args) { String str = "This is a test"; // Test str, if it starts with "This" if (str.startsWith("This")) { System.out.println("String starts with This"); } else { System.out.println("String does not start with This"); } // Test str, if it ends with "program" if (str.endsWith("program")) { System.out.println("String ends with program"); } else { System.out.println("String does not end with program"); } } }
上面的代碼生成以下結(jié)果。
更多建議: