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

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)中,我們要查找的字符串作為正則表達式傳遞,而不是簡單的字符串。但我稍後會講到。”