Java-String中常用方法彙總及解析

  Java不愧有高級語言的高級語言之稱,對比於C,Java將String中常見操作進行了封裝,使用戶之間調用方法就行了,這當然要歸功JDK。而C面對的String和基本數據類型並不不同,要自己手寫底層的操作。以下就是Java-String常用方法,應用場景,及解析。

1,char charAt(int index) 返回指定索引處的 char 值。

在這裏插入圖片描述
源碼解析:

public char charAt(int index) {
        if ((index < 0) || (index >= value.length)) {
            throw new StringIndexOutOfBoundsException(index);
        }
        return value[index];
 }

沒想到這麼簡單吧,直接返回了數組內元素了,這是怎麼回事,value[]從哪來的?
在這裏插入圖片描述
原來,String是披着字符串外衣的字符數組啊,穿上馬甲我就不認識你了。final修飾很好理解,字符串一旦定義了就不能更改了。

注意:index索引是數組下標,從零開始。第一位的index爲0。

2,int indexOf(String str): 返回指定字符在字符串中第一次出現處的索引,如果此字符串中沒有這樣的字符,則返回 -1。

在這裏插入圖片描述

源碼解析:

   static int indexOf(char[] source, int sourceOffset, int sourceCount,
            char[] target, int targetOffset, int targetCount,
            int fromIndex) {
        if (fromIndex >= sourceCount) {
            return (targetCount == 0 ? sourceCount : -1);
        }
        if (fromIndex < 0) {
            fromIndex = 0;
        }
        if (targetCount == 0) {
            return fromIndex;
        }
    char first = target[targetOffset];
    int max = sourceOffset + (sourceCount - targetCount);

    for (int i = sourceOffset + fromIndex; i <= max; i++) {
        /* Look for first character. */
        if (source[i] != first) {
            while (++i <= max && source[i] != first);
        }

        /* Found first character, now look at the rest of v2 */
        if (i <= max) {
            int j = i + 1;
            int end = j + targetCount - 1;
            for (int k = targetOffset + 1; j < end && source[j]
                    == target[k]; j++, k++);

            if (j == end) {
                /* Found whole string. */
                return i - sourceOffset;
            }
        }
    }
    return -1;
}

算法
1)找出倆(母子 )字符串中,母串中首次與子串第一個字符相等的下標索引m;
2)從索引m開始遍歷,判斷後面的字符是否相等;
3)如何判斷相等?設置兩個頭尾指針(頭指針指向m+1;尾指針指向m+子串長度),當頭指針到達尾指針的位置,或者遍歷過程中存在字符不相等的情況,則跳出循環;再找下一個相等索引m。
4)判斷頭指針等於尾指針,等於則返回頭指針前一個位置;否則返回-1。

應用場景:判斷某字符串是否爲另一字符串的子串。

3,char[] toCharArray() 將此字符串轉換爲一個新的字符數組。

在這裏插入圖片描述

源碼解析:

public char[] toCharArray() {
        // Cannot use Arrays.copyOf because of class initialization order issues
        char result[] = new char[value.length];
        System.arraycopy(value, 0, result, 0, value.length);
        return result;
    }

創建一個新字符數組,將原字符串(字符數組)copy到新數組上,返回新數組。

應用場景:經常是對字符串拆分,對其字符進行操作。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章