首页javastringJava Data Type - 如何搜索字符串

Java Data Type - 如何搜索字符串

我们想知道如何搜索字符串。

We can get the index of a character or a string within another string using the indexOf() and lastIndexOf() methods. For example,

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); } }