1.比較字符串

字符串最常見的操作之一是比較。String 類有十多種不同的方法,用於將一個字符串與另一個字符串進行比較。下面我們將看看其中的七個主要部分。

方法 描述
boolean equals(String str)
如果所有字符都匹配,則字符串被認為是相等的。
boolean equalsIgnoreCase(String str)
比較字符串,忽略字母的大小寫(忽略它們是大寫還是小寫)
int compareTo(String str)
按字典順序比較字符串。如果字符串相等,則返回 0。如果當前字符串小於字符串參數,則返回值小於零。如果當前字符串大於字符串參數,則返回值大於。
int compareToIgnoreCase(String str)
在忽略大小寫的情況下按字典順序比較字符串。如果字符串相等,則返回 0。如果當前字符串小於字符串參數,則返回值為負。如果當前字符串大於字符串參數,則返回值大於。
boolean regionMatches(int toffset, String str, int offset, int len)
比較部分字符串
boolean startsWith(String prefix)
檢查當前字符串是否以該字符串開頭prefix
boolean endsWith(String suffix)
檢查當前字符串是否以該字符串結尾suffix

假設您想編寫一個程序,要求用戶提供文件路徑,然後根據擴展名檢查文件類型。此類程序的代碼可能如下所示:

代碼 筆記
Scanner console = new Scanner(System.in);
String path = console.nextLine();

if (path.endsWith(".jpg") || path.endsWith(".jpeg"))
{
   System.out.println("This is a jpeg!");
}
else if (path.endsWith(".htm") || path.endsWith(".html"))
{
   System.out.println("This is an HTML page");
}
else if (path.endsWith(".doc") || path.endsWith(".docx"))
{
   System.out.println("This is a Word document");
}
else
{
   System.out.println("Unknown format");
}
創建一個Scanner對象
從控制台讀取一行

檢查字符串是否path以給定的字符串結尾


2.搜索子串

在比較字符串之後,第二個最流行的操作是在另一個字符串中查找一個字符串。String 類也為此提供了一些方法:

方法 描述
int indexOf(String str)
str在當前字符串中搜索字符串。返回第一次出現的第一個字符的索引。
int indexOf(String str, int index)
str在當前字符串中搜索字符串,跳過第一個index字符。返回出現的索引。
int lastIndexOf(String str)
在當前字符串中搜索字符串str,從末尾開始。返回第一次出現的索引。
int lastIndexOf(String str, int index)
str從末尾搜索當前字符串中的字符串,跳過第一個index字符。
boolean matches(String regex)
檢查當前字符串是否與正則表達式指定的模式匹配。

和方法經常結合使用indexOf(String)indexOf(String, index)第一個方法讓您找到當前字符串中傳遞的子字符串的第一次出現。第二種方法允許您通過跳過第一個索引字符來查找第二個、第三個等事件。

假設我們有一個像“ https://domain.com/about/reviews ”這樣的 url ,我們想用“ codegym.cc ”替換域名。網址可以有各種不同的域名,但我們知道以下內容:

  • 域名前面有兩個正斜杠 - " //"
  • 域名後跟一個正斜杠 - " /"

此類程序的代碼如下所示:

代碼 筆記
Scanner console = new Scanner(System.in);
String path = console.nextLine();

int index = path.indexOf("//");
int index2 = path.indexOf("/", index + 2);

String first = path.substring(0, index + 2);
String last = path.substring(index2);

String result = first + "codegym.cc" + last;
System.out.println(result);
創建一個 Scanner 對象
從控制台讀取一行

獲取字符串“ //”第一次出現的
索引 我們獲取字符串第一次出現的索引/,但只在字符出現後查看//
我們從字符的開頭到結尾獲取字符串我們從字符的結尾//
獲取字符串。 我們連接字符串和新域。 /

和方法lastIndexOf(String)lastIndexOf(String, index)工作方式相同,只是從字符串的末尾到開頭執行搜索。



3. 創建子串

除了比較字符串和查找子串之外,還有一個非常流行的動作:從字符串中獲取子串。碰巧的是,前面的示例向您展示了一個substring()返回部分字符串的方法調用。

以下是從當前字符串返回子字符串的 8 種方法的列表:

方法 描述
String substring(int beginIndex, int endIndex)
返回索引範圍指定的子字符串beginIndex..endIndex
String repeat(int count)
重複當前字符串 n 次
String replace(char oldChar, char newChar)
返回一個新字符串:oldChar用字符替換字符newChar
String replaceFirst(String regex, String replacement)
替換當前字符串中由正則表達式指定的第一個子字符串。
String replaceAll(String regex, String replacement)
替換當前字符串中與正則表達式匹配的所有子字符串。
String toLowerCase()
將字符串轉換為小寫
String toUpperCase()
將字符串轉換為大寫
String trim()
刪除字符串開頭和結尾的所有空格

以下是可用方法的摘要:

substring(int beginIndex, int endIndex)方法

substring方法返回一個新字符串,該字符串由當前字符串中的字符組成,從具有索引的字符開始,beginIndexendIndex. 與 Java 中的所有間隔一樣,具有索引的字符endIndex不包含在間隔中。例子:

代碼 結果
"Hellos".substring(0, 3);
"Hel"
"Hellos".substring(1, 4);
"ell"
"Hellos".substring(1, 6);
"ellos"
"Hellos".substring(1);
"ellos"

如果endIndex未指定參數(這是可能的),則子字符串將從 beginIndex 處的字符獲取到字符串的末尾。

repeat(int n)方法

repeat 方法簡單地重複當前字符串的n次數。例子:

代碼 結果
"Hello".repeat(3);
"HelloHelloHello"
"Hello".repeat(2);
"HelloHello"
"Hello".repeat(1);
"Hello"
"Hello".repeat(0);
""

replace(char oldChar, char newChar)方法

replace()方法返回一個新字符串,其中所有字符oldChar都替換為字符newChar。這不會改變字符串的長度。例子:

代碼 結果
"Programming".replace('Z', 'z');
"Programming"
"Programming".replace('g', 'd');
"Prodrammind"
"Programming".replace('a', 'e');
"Progremming"
"Programming".replace('m', 'w');
"Prograwwing"

replaceFirst()replaceAll()方法

replaceAll()方法將所有出現的一個子字符串替換為另一個子字符串。該replaceFirst()方法用指定的子字符串替換第一次出現的傳遞的子字符串。要替換的字符串由正則表達式指定。我們將在Java 多線程任務中深入研究正則表達式。

例子:

代碼 結果
"Good news everyone!".replaceAll("e.", "EX");
"Good nEXs EXEXyonEX"
"Good news everyone!".replaceAll("o.", "-o-");
"G-o-d news every-o-e!"
"Good news everyone!".replaceFirst("e.", "EX");
"Good nEXs everyone!"
"Good news everyone!".replaceFirst("o.", "-o-");
"G-o-d news everyone!"

toLowerCase() and toUpperCase()方法

當我們第一次學習調用類的方法時,我們就知道了這些方法String

trim()方法

trim()方法從字符串中刪除前導和尾隨空格。不接觸字符串內的空格(即不在開頭或結尾)。例子:

代碼 結果
"     ".trim();
""
"Hello".trim();
"Hello"
" Hello\n how are you?\n   ".trim();
"Hello\n how are you?\n"
"  Password\n   \n ".trim();
"Password\n   \n"