Analysis of common methods in String class from source code

0. Construction method

There are many methods to construct strings, which can be constructed by String, byte, char, int, StringBuffer, StringBuilder and other data types. Some construction methods are as follows:

  • String(): initializes the newly created string object to represent a null character sequence.
public String() {
        this.value = "".value;
    }
Copy code
  • String(String original): initialize the newly created string object to represent the same character sequence as the parameter.
public String(String original) {
        this.value = original.value;
        this.hash = original.hash;
    }
Copy code
  • String(byte[] bytes): construct a new string by decoding the specified byte array using the platform's default character set.
public String(byte bytes[]) {
        this(bytes, 0, bytes.length);
    }
Copy code
  • String(byte[] bytes, Charset charset): construct a new string and decode charset with the specified byte array.
public String(byte bytes[], Charset charset) {
        this(bytes, 0, bytes.length, charset);
    }
Copy code
  • String(char value []): allocate a new string so that it represents the character sequence currently contained in the character array parameter.
public String(char value[]) {
        this.value = Arrays.copyOf(value, value.length);
    }
Copy code
  • String(StringBuffer buffer): allocate a new string containing the character sequence currently contained in the buffer parameter.
public String(StringBuffer buffer) {
        synchronized(buffer) {
            this.value = Arrays.copyOf(buffer.getValue(), buffer.length());
        }
    }
Copy code
  • String (StringBuilder): assign a new string containing the character sequence currently contained in the builder parameter.
public String(StringBuilder builder) {
        this.value = Arrays.copyOf(builder.getValue(), builder.length());
    }
Copy code

Scan VX for Java data, front-end, test, python and so on

1.char charAt(int index)

Returns the character in the string at the specified index index.

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

The definition of value is as follows:

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

One construction method of String class is:

public String(String original) {
        this.value = original.value;
        this.hash = original.hash;
    }
Copy code

It can be seen that the underlying string is actually stored by an immutable character array decorated with the final keyword. String.charAt(index) returns value[index].

2.int compareTo(String anotherString)

Compare two strings character by character. If the first character is equal to the first character of the parameter, compare the second character with the second character of the parameter, and so on until they are unequal, and return the ASCII code difference of the character. If two strings are not of the same length and the corresponding characters are exactly the same, the length difference between the two strings is returned.

		 * @param   anotherString   the {@code String} to be compared.
     * @return  the value {@code 0} if the argument string is equal to
     *          this string; a value less than {@code 0} if this string
     *          is lexicographically less than the string argument; and a
     *          value greater than {@code 0} if this string is
     *          lexicographically greater than the string argument.
     */
    public int compareTo(String anotherString) {
        int len1 = value.length;
        int len2 = anotherString.value.length;
        int lim = Math.min(len1, len2);
        char v1[] = value;
        char v2[] = anotherString.value;

        int k = 0;
        while (k < lim) {		//Character by character comparison
            char c1 = v1[k];
            char c2 = v2[k];
            if (c1 != c2) {
                return c1 - c2;	//If the characters in the same position are not equal, the ASCII code difference of the character is returned
            }
            k++;
        }
        return len1 - len2;		//If two strings are not of the same length and the corresponding characters are exactly the same, the length difference between the two strings is returned
    }
Copy code

3.String concat(String str)

Splices the specified string to the end of the string.

*
     * @param   str   the {@code String} that is concatenated to the end
     *                of this {@code String}.
     * @return  a string that represents the concatenation of this object's
     *          characters followed by the string argument's characters.
     */
    public String concat(String str) {
        if (str.isEmpty()) {
            return this;
        }
        int len = value.length;
        int otherLen = str.length();
        char buf[] = Arrays.copyOf(value, len + otherLen);
        str.getChars(buf, len);
        return new String(buf, true);
    }
Copy code

4.boolean contains(CharSequence s)

Returns true if and only if this string contains the specified CharSequence.

*
     * @param s the sequence to search for
     * @return true if this string contains {@code s}, false otherwise
     * @since 1.5
     */
    public boolean contains(CharSequence s) {
        return indexOf(s.toString()) > -1;
    }
Copy code

CharSequence is an interface that describes the string structure. String, StringBuilder and StringBuffer are all its sub interfaces.

5.boolean startsWith(String prefix, int toffset)

Tests whether the substring of this string starting at the specified index begins with the specified prefix. toffset is the specified start index

public boolean startsWith(String prefix, int toffset) {
        char ta[] = value;
        int to = toffset;
        char pa[] = prefix.value;
        int po = 0;
        int pc = prefix.value.length;
        // Note: toffset might be near -1>>>1.
        if ((toffset < 0) || (toffset > value.length - pc)) {
            return false;
        }
        while (--pc >= 0) {
            if (ta[to++] != pa[po++]) {
                return false;
            }
        }
        return true;
    }
Copy code

6.boolean endsWith(String suffix)

Tests whether the string ends with the specified suffix.

public boolean endsWith(String suffix) {
				//Call the startsWith method, which is equivalent to starting from value length - suffix. value. Comparison at length index
        return startsWith(suffix, value.length - suffix.value.length);
    }
Copy code

7.boolean equals(Object anObject)

Compares this string with the specified object.

public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }
Copy code

Scan VX for Java data, front-end, test, python and so on

8.String format(String format, Object... args)

Returns a formatted string using the specified format string and parameters.

9.byte[] getBytes()

Use the platform's default character set to encode this String into a byte sequence and store the result in a new byte array.

public byte[] getBytes() {
        return StringCoding.encode(value, 0, value.length);
    }
Copy code

10.int hashCode()

Returns the hash code of this string.

public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;

            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }
Copy code

11.int indexOf(int ch)

Returns the index within the string where the specified character first appears.

12.int lastIndexOf(int ch)

Returns the index of the last occurrence of a specified character in a string.

13.boolean isEmpty()

Returns true if and only if length() is 0.

public boolean isEmpty() {
        return value.length == 0;
    }
Copy code

14.int length()

Returns the length of this string.

public int length() {
        return value.length;
    }
Copy code

15.boolean matches(String regex)

Tells whether the string matches the given regular expression.

public boolean matches(String regex) {
        return Pattern.matches(regex, this);
    }
Copy code

16.String replaceAll(String regex, String replacement)

Replace each substring that matches the given regular expression with the given string.

17.String replaceFirst(String regex, String replacement)

Replaces the first substring that matches the given regular expression with the given string.

18.String[] split(String regex)

Splits this string into a match for the given regular expression. Returns an array of split strings.

public String[] split(String regex) {
        return split(regex, 0);
    }
public String[] split(String regex, int limit) {
        /* fastpath if the regex is a
         (1)one-char String and this character is not one of the
            RegEx's meta characters ".$|()[{^?*+\\", or
         (2)two-char String and the first char is the backslash and
            the second is not the ascii digit or ascii letter.
         */
        char ch = 0;
        if (((regex.value.length == 1 &&
             ".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||
             (regex.length() == 2 &&
              regex.charAt(0) == '\\' &&
              (((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&
              ((ch-'a')|('z'-ch)) < 0 &&
              ((ch-'A')|('Z'-ch)) < 0)) &&
            (ch < Character.MIN_HIGH_SURROGATE ||
             ch > Character.MAX_LOW_SURROGATE))
        {
            int off = 0;
            int next = 0;
            boolean limited = limit > 0;
            ArrayList<String> list = new ArrayList<>();
            while ((next = indexOf(ch, off)) != -1) {
                if (!limited || list.size() < limit - 1) {
                    list.add(substring(off, next));
                    off = next + 1;
                } else {    // last one
                    //assert (list.size() == limit - 1);
                    list.add(substring(off, value.length));
                    off = value.length;
                    break;
                }
            }
            // If no match was found, return this
            if (off == 0)
                return new String[]{this};

            // Add remaining segment
            if (!limited || list.size() < limit)
                list.add(substring(off, value.length));

            // Construct result
            int resultSize = list.size();
            if (limit == 0) {
                while (resultSize > 0 && list.get(resultSize - 1).isEmpty()) {
                    resultSize--;
                }
            }
            String[] result = new String[resultSize];
            return list.subList(0, resultSize).toArray(result);
        }
        return Pattern.compile(regex).split(this, limit);
    }
Copy code

19.String substring(int beginIndex, int endIndex)

Returns a string (the string between the index beginIndex and endIndex) that is a substring of this string.

public String substring(int beginIndex, int endIndex) {
        if (beginIndex < 0) {
            throw new StringIndexOutOfBoundsException(beginIndex);
        }
        if (endIndex > value.length) {
            throw new StringIndexOutOfBoundsException(endIndex);
        }
        int subLen = endIndex - beginIndex;
        if (subLen < 0) {
            throw new StringIndexOutOfBoundsException(subLen);
        }
        return ((beginIndex == 0) && (endIndex == value.length)) ? this
                : new String(value, beginIndex, subLen);
    }
Copy code

20.char[] toCharArray()

Converts this string to a new character array.

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 code

21.String toLowerCase()

Lowercase all characters in this string.

22.String toUpperCase()

Capitalize all characters in this string.

23.String trim()

Delete the leading and trailing whitespace of the string (the middle whitespace will be retained).

public String trim() {
        int len = value.length;
        int st = 0;
        char[] val = value;    /* avoid getfield opcode */

        while ((st < len) && (val[st] <= ' ')) {
            st++;
        }
        while ((st < len) && (val[len - 1] <= ' ')) {
            len--;
        }
        return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
    }
Copy code

24. String valueOf()

Converts the passed in parameter to a string.

  • String.valueOf(boolean b): converts boolean variable B to a string
  • String.valueOf(char c): converts char variable C to a string
  • String.valueOf(char[] data): converts char array data into a string
  • String.valueOf(char[] data, int offset, int count) :

Convert count elements from data[offset] in char array data into strings

  • String.valueOf(double d): converts the double variable d to a string
  • String.valueOf(float f): converts the float variable f to a string
  • String.valueOf(int i): converts the int variable I to a string
  • String.valueOf(long l): converts the long variable l to a string
  • String.valueOf(Object obj): converts obj objects into strings
public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }
    
public static String valueOf(char data[]) {
        return new String(data);
    }
    
public static String valueOf(char data[], int offset, int count) {
        return new String(data, offset, count);
    }
    
public static String valueOf(boolean b) {
        return b ? "true" : "false";
    }
    
public static String valueOf(char c) {
        char data[] = {c};
        return new String(data, true);
    }
    
public static String valueOf(int i) {
        return Integer.toString(i);
    }
    
public static String valueOf(long l) {
        return Long.toString(l);
    }
    
public static String valueOf(float f) {
        return Float.toString(f);
    }
    
public static String valueOf(double d) {
        return Double.toString(d);
    }
                                   

Scan VX for Java data, front-end, test, python and so on

Keywords: Java

Added by evanct on Fri, 24 Dec 2021 10:16:37 +0200