共計 891 個字符,預(yù)計需要花費 3 分鐘才能閱讀完成。
在 Java 中字符串查找的形式有以下幾種:
- 使用 indexOf() 方法:該方法返回指定子字符串第一次出現(xiàn)的索引,如果未找到則返回 -1。
例如:
String str = "Hello, world!";
int index = str.indexOf("world");
System.out.println(index); // 輸出 6
- 使用 lastIndexOf() 方法:該方法返回指定子字符串最后一次出現(xiàn)的索引,如果未找到則返回 -1。
例如:
String str = "Hello, world!";
int index = str.lastIndexOf("o");
System.out.println(index); // 輸出 8
- 使用 contains() 方法:該方法用于判斷字符串中是否包含指定的子字符串,返回 true 或 false。
例如:
String str = "Hello, world!";
boolean contains = str.contains("world");
System.out.println(contains); // 輸出 true
- 使用 matches() 方法:該方法用于判斷字符串是否匹配指定的正則表達(dá)式。
例如:
String str = "Hello, world!";
boolean isMatch = str.matches("Hello.*");
System.out.println(isMatch); // 輸出 true
- 使用 startsWith() 和 endsWith() 方法:這兩個方法分別用于判斷字符串是否以指定的前綴開始或以指定的后綴結(jié)束,返回 true 或 false。
例如:
String str = "Hello, world!";
boolean startsWith = str.startsWith("Hello");
boolean endsWith = str.endsWith("world!");
System.out.println(startsWith); // 輸出 true
System.out.println(endsWith); // 輸出 true
這些方法可以根據(jù)具體的需求選擇合適的方式進行字符串查找。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完