1. 程式人生 > >[源碼] 定義String s="abcd", 求長度

[源碼] 定義String s="abcd", 求長度

string html unit his sent ref equal sequence pri

一般會答: s.length()

看源碼是如何實現的:

    /**
     * Returns the length of this string.
     * The length is equal to the number of <a href="Character.html#unicode">Unicode
     * code units</a> in the string.
     *
     * @return  the length of the sequence of characters represented by this
     *          object.
     */
    public int length() {
        return value.length;
    }

value就是一個字符數組, 即s.length()其實是調用char[]的length屬性

    /** The value is used for character storage. */
    private final char value[];

[源碼] 定義String s="abcd", 求長度