Java的indexof函數(shù)有哪些替代方案

小樊
81
2024-09-30 00:38:17

在Java中,indexOf函數(shù)用于查找字符串中子字符串的第一個(gè)匹配項(xiàng)的索引。如果找不到子字符串,則返回-1。以下是indexOf的一些替代方案:

  1. lastIndexOf:此函數(shù)查找子字符串在字符串中最后一次出現(xiàn)的索引。如果找不到子字符串,則返回-1。

    String str = "Hello, world!";
    int index = str.lastIndexOf("world"); // 返回 7
    
  2. contains:此函數(shù)檢查字符串是否包含指定的子字符串。如果包含,則返回true,否則返回false

    String str = "Hello, world!";
    boolean containsWorld = str.contains("world"); // 返回 true
    
  3. split:此函數(shù)使用指定的分隔符將字符串分割成一個(gè)字符串?dāng)?shù)組。如果字符串不包含分隔符,則返回包含原始字符串的單個(gè)元素?cái)?shù)組。

    String str = "Hello,world!";
    String[] parts = str.split(","); // 返回 ["Hello", "world!"]
    
  4. substring:此函數(shù)返回字符串的子字符串。如果開(kāi)始索引大于結(jié)束索引,則拋出IllegalArgumentException。

    String str = "Hello, world!";
    String subStr = str.substring(0, 5); // 返回 "Hello"
    
  5. equals:此函數(shù)比較兩個(gè)字符串是否相等。如果相等,則返回true,否則返回false。

    String str1 = "Hello, world!";
    String str2 = "Hello, world!";
    boolean areEqual = str1.equals(str2); // 返回 true
    

根據(jù)您的需求,可以選擇適當(dāng)?shù)奶娲桨浮?/p>

0