“看看你可以用子字符串做的其他事情:”

8) 如何找到子串?

indexOf和lastIndexOf方法让您可以在字符串中搜索字符串。这些方法有 4 个版本:

indexOf方法在指定的 String查找字符串。该方法可以从指定字符串的开头搜索字符串,也可以从某个索引开始搜索(第二种方法)。如果找到该字符串,则该方法返回其第一个字符的索引;如果未找到,则返回 -1。

方法) 例子)
int indexOf(String str)
String s = "Good news, everyone!";
int index = s.indexOf ("ne");
结果:

index == 5
int indexOf(String str, int from)
String s = "Good news, everyone!";
int index = s.indexOf ("ne", 7);
结果:

index == 16

" lastIndexOf方法从我们的字符串末尾向后搜索指定的字符串!这个方法可以从我们的字符串的末尾搜索一个字符串,或者从某个索引开始(第二种方法)。如果找到了字符串,那么该方法返回其第一个字符的索引;如果未找到,则返回 -1。”

方法) 例子)
int lastIndexOf(String str)
String s = "Good news, everyone!";
int index = s.lastIndexOf("ne");
结果:

index == 17
int lastIndexOf(String str, int from)
String s = "Good news, everyone!";
int index = s.lastIndexOf("ne", 15);
结果:

index == 5

9) 如何用另一个字符串替换字符串的一部分?

“这有三种方法。”

replace方法用另一个字符替换所有出现的特定字符。

replaceAll 方法用另一个字符串替换所有出现 子字符串。

replaceFirst 方法用指定的字符串替换第一次出现的传递 子字符串。

方法) 例子)
String replace(char oldChar, char newChar)
String s = "Good news, everyone!";
String s2 = s.replace>('o', 'a');
结果:

s2 == "Gaad news, everyane!";
String replaceAll(String regex, String replacement)
String s = "Good news, everyone!";
String s2 = s.replaceAll ("ne", "_");
结果:

s2 == "Good _ws, everyo_!";
String replaceFirst(String regex, String replacement)
String s = "Good news, everyone!";
String s2 = s.replaceFirst ("ne", "_");
结果:

s2 == "Good _ws everyone!";

“但是你需要小心这些。在最后两个方法(replaceAll 和 replaceFirst)中,我们要查找的字符串作为正则表达式传递,而不是简单的字符串。但我稍后会讲到。”