溫馨提示×

如何自定義Java中的indexOf方法

小樊
83
2024-08-21 01:19:28
欄目: 編程語言

要自定義Java中的indexOf方法,可以編寫一個自定義的類,并在其中實(shí)現(xiàn)一個名為indexOf的靜態(tài)方法來代替Java中的String或List類中的indexOf方法。以下是一個示例代碼:

public class CustomIndexOf {

    public static int indexOf(String str, char ch) {
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == ch) {
                return i;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        String str = "Hello, World!";
        char ch = 'o';
        
        int index = indexOf(str, ch);
        
        if (index != -1) {
            System.out.println("Index of '" + ch + "' in '" + str + "' is: " + index);
        } else {
            System.out.println("'" + ch + "' not found in '" + str + "'.");
        }
    }
}

在上面的代碼中,我們自定義了一個indexOf方法來查找字符串中某個字符的索引位置,并在main方法中調(diào)用該方法進(jìn)行測試??梢愿鶕?jù)需求自定義indexOf方法的邏輯和參數(shù),以滿足特定的需求。

0