java源码详解——String类目录:

  • Java String 类
  • 下面开始介绍主要方法:
  • Java charAt() 方法
  • Java compareTo() 方法
  • int compareTo(String anotherString) 方法
  • Java compareToIgnoreCase() 方法
  • Java concat() 方法
  • Java contentEquals() 方法
  • Java copyValueOf() 方法
  • Java endsWith() 方法
  • Java String equals() 方法
  • Java equalsIgnoreCase() 方法
  • Java getBytes() 方法
  • Java getChars() 方法
  • Java hashCode() 方法
  • Java String indexOf() 方法
  • Java intern() 方法
  • Java lastIndexOf() 方法
  • Java String length() 方法
  • Java matches() 方法
  • Java regionMatches() 方法
  • Java replace() 方法
  • Java replaceAll() 方法
  • Java replaceFirst() 方法
  • Java split() 方法
  • Java startsWith() 方法
  • Java subSequence() 方法
  • Java toCharArray() 方法
  • Java toLowerCase() 方法
  • Java toString() 方法
  • Java toUpperCase() 方法
  • Java trim() 方法
  • Java valueOf() 方法
  • Java String contains() 方法
  • Java String isEmpty() 方法


Java String 类

字符串广泛应用 在 Java 编程中,在 Java 中字符串属于对象,Java 提供了 String 类来创建和操作字符串。

下面开始介绍主要方法:

Java charAt() 方法

charAt() 方法用于返回指定索引处的字符。索引范围为从 0 到 length() - 1。

菜鸟教程Java charAt() 方法实例

中文翻译:

返回指定索引处的char值。 索引范围从0到length() - 1 。 序列的第一个char值在索引0 ,下一个在索引1 ,依此类推,对于数组索引。
如果索引指定的char值是surrogate ,则返回代理值。
参数:
index – char值的索引。
返回值:
此字符串的指定索引处的char值。 第一个char值位于索引0 。
顶:
IndexOutOfBoundsException – 如果index参数为负或不小于此字符串的长度。

/**
     * Returns the {@code char} value at the
     * specified index. An index ranges from {@code 0} to
     * {@code length() - 1}. The first {@code char} value of the sequence
     * is at index {@code 0}, the next at index {@code 1},
     * and so on, as for array indexing.
     *
     * <p>If the {@code char} value specified by the index is a
     * <a href="Character.html#unicode">surrogate</a>, the surrogate
     * value is returned.
     *
     * @param      index   the index of the {@code char} value.
     * @return     the {@code char} value at the specified index of this string.
     *             The first {@code char} value is at index {@code 0}.
     * @exception  IndexOutOfBoundsException  if the {@code index}
     *             argument is negative or not less than the length of this
     *             string.
     */
    public char charAt(int index) {
        if ((index < 0) || (index >= value.length)) {
            throw new StringIndexOutOfBoundsException(index);
        }
        return value[index];
    }

Java compareTo() 方法

compareTo() 方法用于两种方式的比较:

字符串与对象进行比较。
按字典顺序比较两个字符串。

菜鸟教程Java compareTo() 方法实例

中文翻译:

将此字符串与指定的对象进行比较。 当且仅当参数不为null并且是表示与此对象相同的字符序列的String对象时,结果才为true 。
参数:
anObject – 要与此String进行比较的对象
返回值:
true如果给定对象表示String等同于这个字符串, false ,否则
请参见:
compareTo(String) , equalsIgnoreCase(String)

/**
     * Compares this string to the specified object.  The result is {@code
     * true} if and only if the argument is not {@code null} and is a {@code
     * String} object that represents the same sequence of characters as this
     * object.
     *
     * @param  anObject
     *         The object to compare this {@code String} against
     *
     * @return  {@code true} if the given object represents a {@code String}
     *          equivalent to this string, {@code false} otherwise
     *
     * @see  #compareTo(String)
     * @see  #equalsIgnoreCase(String)
     */
    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;
    }

int compareTo(String anotherString) 方法

按字典顺序比较两个字符串。

中文翻译:

按字典顺序比较两个字符串。 比较基于字符串中每个字符的 Unicode 值。 此String对象表示的字符序列按字典顺序与参数字符串表示的字符序列进行比较。 如果此String对象按字典顺序位于参数字符串之前,则结果为负整数。 如果此String对象按字典顺序跟在参数字符串之后,则结果为正整数。 如果字符串相等,则结果为零; 当equals(Object)方法返回true时, compareTo返回0 。
这是字典排序的定义。 如果两个字符串不同,那么它们要么在对两个字符串都是有效索引的某个索引处具有不同的字符,要么它们的长度不同,或者两者都有。 如果它们在一个或多个索引位置有不同的字符,则令k为最小的此类索引; 则在位置k处的字符具有较小值的字符串(通过使用 < 运算符确定)按字典顺序排在另一个字符串之前。 在这种情况下, compareTo返回两个字符串中位置k处的两个字符值的差——即值:
this.charAt(k)-anotherString.charAt(k)

如果没有它们不同的索引位置,则较短的字符串按字典顺序排在较长的字符串之前。 在这种情况下, compareTo返回字符串长度的差值——即值:
this.length()-anotherString.length()

参数:
anotherString – 要比较的String 。
返回值:
如果参数字符串等于此字符串,则值为0 ; 如果此字符串按字典顺序小于字符串参数,则为小于0的值; 如果此字符串按字典顺序大于字符串参数,则为大于0的值。

/**
     * Compares two strings lexicographically.
     * The comparison is based on the Unicode value of each character in
     * the strings. The character sequence represented by this
     * {@code String} object is compared lexicographically to the
     * character sequence represented by the argument string. The result is
     * a negative integer if this {@code String} object
     * lexicographically precedes the argument string. The result is a
     * positive integer if this {@code String} object lexicographically
     * follows the argument string. The result is zero if the strings
     * are equal; {@code compareTo} returns {@code 0} exactly when
     * the {@link #equals(Object)} method would return {@code true}.
     * <p>
     * This is the definition of lexicographic ordering. If two strings are
     * different, then either they have different characters at some index
     * that is a valid index for both strings, or their lengths are different,
     * or both. If they have different characters at one or more index
     * positions, let <i>k</i> be the smallest such index; then the string
     * whose character at position <i>k</i> has the smaller value, as
     * determined by using the < operator, lexicographically precedes the
     * other string. In this case, {@code compareTo} returns the
     * difference of the two character values at position {@code k} in
     * the two string -- that is, the value:
     * <blockquote><pre>
     * this.charAt(k)-anotherString.charAt(k)
     * </pre></blockquote>
     * If there is no index position at which they differ, then the shorter
     * string lexicographically precedes the longer string. In this case,
     * {@code compareTo} returns the difference of the lengths of the
     * strings -- that is, the value:
     * <blockquote><pre>
     * this.length()-anotherString.length()
     * </pre></blockquote>
     *
     * @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) {
            char c1 = v1[k];
            char c2 = v2[k];
            if (c1 != c2) {
                return c1 - c2;
            }
            k++;
        }
        return len1 - len2;
    }

Java compareToIgnoreCase() 方法

compareToIgnoreCase() 方法用于按字典顺序比较两个字符串,不考虑大小写。

菜鸟教程Java compareToIgnoreCase() 方法实例

中文翻译:

按字典顺序比较两个字符串,忽略大小写差异。 此方法返回一个整数,其符号是使用字符串的规范化版本调用compareTo的符号,其中通过对每个字符调用Character.toLowerCase(Character.toUpperCase(character))消除了大小写差异。
注意,此方法没有考虑区域考虑,并会导致特定的语言环境不满意的排序。 java.text 包提供了整理器以允许区分区域设置的排序。
参数:
str – 要比较的String 。
返回值:
负整数、零或正整数,因为指定的字符串大于、等于或小于此字符串,忽略大小写考虑。
自:
1.2
请参见:
java.text.Collator.compare(String, String)

/**
     * Compares two strings lexicographically, ignoring case
     * differences. This method returns an integer whose sign is that of
     * calling {@code compareTo} with normalized versions of the strings
     * where case differences have been eliminated by calling
     * {@code Character.toLowerCase(Character.toUpperCase(character))} on
     * each character.
     * <p>
     * Note that this method does <em>not</em> take locale into account,
     * and will result in an unsatisfactory ordering for certain locales.
     * The java.text package provides <em>collators</em> to allow
     * locale-sensitive ordering.
     *
     * @param   str   the {@code String} to be compared.
     * @return  a negative integer, zero, or a positive integer as the
     *          specified String is greater than, equal to, or less
     *          than this String, ignoring case considerations.
     * @see     java.text.Collator#compare(String, String)
     * @since   1.2
     */
    public int compareToIgnoreCase(String str) {
        return CASE_INSENSITIVE_ORDER.compare(this, str);
    }

Java concat() 方法

concat() 方法用于将指定的字符串参数连接到字符串上。

菜鸟教程Java concat() 方法实例

中文翻译:

将指定的字符串连接到此字符串的末尾。
如果参数字符串的长度为0 ,则返回此String对象。 否则,返回一个String对象,该对象表示一个字符序列,该字符序列是由该String对象表示的字符序列和由参数字符串表示的字符序列的串联。
例子:
“cares”.concat(“s”) returns “caress”
“to”.concat(“get”).concat(“her”) returns “together”

参数:
STR -该String被连结到该结束String 。
返回值:
一个字符串,表示此对象的字符后跟字符串参数的字符的串联。

/**
     * Concatenates the specified string to the end of this string.
     * <p>
     * If the length of the argument string is {@code 0}, then this
     * {@code String} object is returned. Otherwise, a
     * {@code String} object is returned that represents a character
     * sequence that is the concatenation of the character sequence
     * represented by this {@code String} object and the character
     * sequence represented by the argument string.<p>
     * Examples:
     * <blockquote><pre>
     * "cares".concat("s") returns "caress"
     * "to".concat("get").concat("her") returns "together"
     * </pre></blockquote>
     *
     * @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);
    }

Java contentEquals() 方法

contentEquals() 方法用于将此字符串与指定的 StringBuffer 比较。

菜鸟教程Java contentEquals() 方法实例

中文翻译:

将此字符串与指定的StringBuffer 。 当且仅当此String表示与指定的StringBuffer相同的字符序列时,结果为true 。 此方法在StringBuffer上同步。
参数:
sb – 与此String进行比较的StringBuffer
返回值:如果此String表示与指定的StringBuffer相同的字符序列,则为true ,否则为false

/**
     * Compares this string to the specified {@code StringBuffer}.  The result
     * is {@code true} if and only if this {@code String} represents the same
     * sequence of characters as the specified {@code StringBuffer}. This method
     * synchronizes on the {@code StringBuffer}.
     *
     * @param  sb
     *         The {@code StringBuffer} to compare this {@code String} against
     *
     * @return  {@code true} if this {@code String} represents the same
     *          sequence of characters as the specified {@code StringBuffer},
     *          {@code false} otherwise
     *
     * @since  1.4
     */
    public boolean contentEquals(StringBuffer sb) {
        return contentEquals((CharSequence)sb);
    }

Java copyValueOf() 方法

copyValueOf() 方法有两种形式:

public static String copyValueOf(char[] data): 返回指定数组中表示该字符序列的字符串。

中文翻译:

相当于valueOf(char[]) 。
参数:数据 – 字符数组。
返回值:一个String包含字符阵列的字符。

public static String copyValueOf(char[] data, int offset, int count): 返回指定数组中表示该字符序列的 字符串。

中文翻译:

相当于valueOf(char[], int, int) 。
参数:
数据 – 字符数组。
offset – 子数组的初始偏移量。
count - 子数组的长度。
返回值:一个String ,包含字符数组的指定子数组的字符。
顶:IndexOutOfBoundsException – 如果offset为负数,或count为负数,或offset+count大于data.length 。

菜鸟教程Java copyValueOf() 方法实例

/**
     * Equivalent to {@link #valueOf(char[], int, int)}.
     *
     * @param   data     the character array.
     * @param   offset   initial offset of the subarray.
     * @param   count    length of the subarray.
     * @return  a {@code String} that contains the characters of the
     *          specified subarray of the character array.
     * @exception IndexOutOfBoundsException if {@code offset} is
     *          negative, or {@code count} is negative, or
     *          {@code offset+count} is larger than
     *          {@code data.length}.
     */
    public static String copyValueOf(char data[], int offset, int count) {
        return new String(data, offset, count);
    }

    /**
     * Equivalent to {@link #valueOf(char[])}.
     *
     * @param   data   the character array.
     * @return  a {@code String} that contains the characters of the
     *          character array.
     */
    public static String copyValueOf(char data[]) {
        return new String(data);
    }

Java endsWith() 方法

测试此字符串是否以指定的后缀结束。

菜鸟教程Java endsWith() 方法实例

中文翻译:

测试此字符串是否以指定的后缀结尾。
参数:
后缀 - 后缀。
返回值:
如果参数表示的字符序列是此对象表示的字符序列的后缀,则为true ; 否则为false 。 请注意,如果参数是空字符串或等于由equals(Object)方法确定的此String对象,则结果将为true 。

/**
     * Tests if this string ends with the specified suffix.
     *
     * @param   suffix   the suffix.
     * @return  {@code true} if the character sequence represented by the
     *          argument is a suffix of the character sequence represented by
     *          this object; {@code false} otherwise. Note that the
     *          result will be {@code true} if the argument is the
     *          empty string or is equal to this {@code String} object
     *          as determined by the {@link #equals(Object)} method.
     */
    public boolean endsWith(String suffix) {
        return startsWith(suffix, value.length - suffix.value.length);
    }

Java String equals() 方法

equals() 方法用于将字符串与指定的对象比较。

String 类中重写了 equals() 方法用于比较两个字符串的内容是否相等。

菜鸟教程Java String equals() 方法实例

中文翻译:

将此字符串与指定的对象进行比较。 当且仅当参数不为null并且是表示与此对象相同的字符序列的String对象时,结果才为true 。
参数:
anObject – 要与此String进行比较的对象
返回值:
true如果给定对象表示String等同于这个字符串, false ,否则
请参见:
compareTo(String) , equalsIgnoreCase(String)

/**
     * Compares this string to the specified object.  The result is {@code
     * true} if and only if the argument is not {@code null} and is a {@code
     * String} object that represents the same sequence of characters as this
     * object.
     *
     * @param  anObject
     *         The object to compare this {@code String} against
     *
     * @return  {@code true} if the given object represents a {@code String}
     *          equivalent to this string, {@code false} otherwise
     *
     * @see  #compareTo(String)
     * @see  #equalsIgnoreCase(String)
     */
    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;
    }

Java equalsIgnoreCase() 方法

equalsIgnoreCase() 方法用于将字符串与指定的对象比较,不考虑大小写。

菜鸟教程Java equalsIgnoreCase() 方法实例

中文翻译:

将此String与另一个String比较,忽略大小写考虑。 如果两个字符串的长度相同并且两个字符串中对应的字符是相等的忽略大小写,则认为两个字符串是相等的忽略大小写。
如果以下至少一项为真,则两个字符c1和c2被认为是相同的忽略大小写:
两个字符相同(由==运算符比较)
将方法Character.toUpperCase(char)应用于每个字符会产生相同的结果
将方法Character.toLowerCase(char)应用于每个字符会产生相同的结果
参数:
anotherString – 与此String进行比较的String
返回值:
如果参数不为null并且它表示等效的String忽略大小写,则为true ; 否则为false
请参见:
equals(Object)

/**
     * Compares this {@code String} to another {@code String}, ignoring case
     * considerations.  Two strings are considered equal ignoring case if they
     * are of the same length and corresponding characters in the two strings
     * are equal ignoring case.
     *
     * <p> Two characters {@code c1} and {@code c2} are considered the same
     * ignoring case if at least one of the following is true:
     * <ul>
     *   <li> The two characters are the same (as compared by the
     *        {@code ==} operator)
     *   <li> Applying the method {@link
     *        java.lang.Character#toUpperCase(char)} to each character
     *        produces the same result
     *   <li> Applying the method {@link
     *        java.lang.Character#toLowerCase(char)} to each character
     *        produces the same result
     * </ul>
     *
     * @param  anotherString
     *         The {@code String} to compare this {@code String} against
     *
     * @return  {@code true} if the argument is not {@code null} and it
     *          represents an equivalent {@code String} ignoring case; {@code
     *          false} otherwise
     *
     * @see  #equals(Object)
     */
    public boolean equalsIgnoreCase(String anotherString) {
        return (this == anotherString) ? true
                : (anotherString != null)
                && (anotherString.value.length == value.length)
                && regionMatches(true, 0, anotherString, 0, value.length);
    }

Java getBytes() 方法

菜鸟教程Java getBytes() 方法实例

getBytes() 方法有两种形式:

getBytes(String charsetName): 使用指定的字符集将字符串编码为 byte 序列,并将结果存储到一个新的 byte 数组中。

中文翻译:

使用命名字符集将此String编码为字节序列,并将结果存储到新的字节数组中。
当此字符串无法在给定字符集中编码时,此方法的行为未指定。 当需要对编码过程进行更多控制时,应使用java.nio.charset.CharsetEncoder类。
参数:
charsetName – 支持的字符集的名称
返回值:
结果字节数组
顶:
UnsupportedEncodingException – 如果不支持指定的字符集
自:
JDK1.1

/**
     * Encodes this {@code String} into a sequence of bytes using the named
     * charset, storing the result into a new byte array.
     *
     * <p> The behavior of this method when this string cannot be encoded in
     * the given charset is unspecified.  The {@link
     * java.nio.charset.CharsetEncoder} class should be used when more control
     * over the encoding process is required.
     *
     * @param  charsetName
     *         The name of a supported {@linkplain java.nio.charset.Charset
     *         charset}
     *
     * @return  The resultant byte array
     *
     * @throws  UnsupportedEncodingException
     *          If the named charset is not supported
     *
     * @since  JDK1.1
     */
    public byte[] getBytes(String charsetName)
            throws UnsupportedEncodingException {
        if (charsetName == null) throw new NullPointerException();
        return StringCoding.encode(charsetName, value, 0, value.length);
    }

getBytes(): 使用平台的默认字符集将字符串编码为 byte 序列,并将结果存储到一个新的 byte 数组中。

中文翻译:

使用平台的默认字符集将此String编码为字节序列,并将结果存储到新的字节数组中。
当此字符串无法在默认字符集中编码时,此方法的行为未指定。 当需要对编码过程进行更多控制时,应使用java.nio.charset.CharsetEncoder类。
返回值:
结果字节数组
自:
JDK1.1

/**
     * Encodes this {@code String} into a sequence of bytes using the
     * platform's default charset, storing the result into a new byte array.
     *
     * <p> The behavior of this method when this string cannot be encoded in
     * the default charset is unspecified.  The {@link
     * java.nio.charset.CharsetEncoder} class should be used when more control
     * over the encoding process is required.
     *
     * @return  The resultant byte array
     *
     * @since      JDK1.1
     */
    public byte[] getBytes() {
        return StringCoding.encode(value, 0, value.length);
    }

Java getChars() 方法

getChars() 方法将字符从字符串复制到目标字符数组。

菜鸟教程Java getChars() 方法实例

中文翻译:

将此字符串中的字符复制到目标字符数组中。
要复制的第一个字符位于索引srcBegin ; 要复制的最后一个字符位于索引srcEnd-1 (因此要复制的字符总数为srcEnd-srcBegin )。 字符被复制到dst的子dstBegin ,从索引dstBegin开始到索引结束:
dstBegin + (srcEnd-srcBegin) - 1

参数:
srcBegin – 要复制的字符串中第一个字符的索引。
srcEnd – 要复制的字符串中最后一个字符之后的索引。
dst – 目标数组。
dstBegin – 目标数组中的起始偏移量。
顶:
IndexOutOfBoundsException – 如果以下任一情况为真:
srcBegin是否定的。
srcBegin大于srcEnd
srcEnd大于这个字符串的长度
dstBegin为负
dstBegin+(srcEnd-srcBegin)大于dst.length

/**
     * Copies characters from this string into the destination character
     * array.
     * <p>
     * The first character to be copied is at index {@code srcBegin};
     * the last character to be copied is at index {@code srcEnd-1}
     * (thus the total number of characters to be copied is
     * {@code srcEnd-srcBegin}). The characters are copied into the
     * subarray of {@code dst} starting at index {@code dstBegin}
     * and ending at index:
     * <blockquote><pre>
     *     dstBegin + (srcEnd-srcBegin) - 1
     * </pre></blockquote>
     *
     * @param      srcBegin   index of the first character in the string
     *                        to copy.
     * @param      srcEnd     index after the last character in the string
     *                        to copy.
     * @param      dst        the destination array.
     * @param      dstBegin   the start offset in the destination array.
     * @exception IndexOutOfBoundsException If any of the following
     *            is true:
     *            <ul><li>{@code srcBegin} is negative.
     *            <li>{@code srcBegin} is greater than {@code srcEnd}
     *            <li>{@code srcEnd} is greater than the length of this
     *                string
     *            <li>{@code dstBegin} is negative
     *            <li>{@code dstBegin+(srcEnd-srcBegin)} is larger than
     *                {@code dst.length}</ul>
     */
    public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
        if (srcBegin < 0) {
            throw new StringIndexOutOfBoundsException(srcBegin);
        }
        if (srcEnd > value.length) {
            throw new StringIndexOutOfBoundsException(srcEnd);
        }
        if (srcBegin > srcEnd) {
            throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
        }
        System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
    }

Java hashCode() 方法

hashCode() 方法用于返回字符串的哈希码。

字符串对象的哈希码根据以下公式计算:

s[0]*31^(n-1) + s[1]*31^(n-2) + … + s[n-1]

使用 int 算法,这里 s[i] 是字符串的第 i 个字符,n 是字符串的长度,^ 表示求幂。空字符串的哈希值为 0。

菜鸟教程Java hashCode() 方法实例

中文翻译:

返回此字符串的哈希码。 String对象的哈希码计算如下
s[0]*31^(n-1) + s[1]*31^(n-2) + … + s[n-1]

使用int算术,其中s[i]是字符串的第i个字符, n是字符串的长度, ^表示求幂。 (空字符串的哈希值为零。)
返回值:
此对象的哈希码值。

/**
     * Returns a hash code for this string. The hash code for a
     * {@code String} object is computed as
     * <blockquote><pre>
     * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
     * </pre></blockquote>
     * using {@code int} arithmetic, where {@code s[i]} is the
     * <i>i</i>th character of the string, {@code n} is the length of
     * the string, and {@code ^} indicates exponentiation.
     * (The hash value of the empty string is zero.)
     *
     * @return  a hash code value for this object.
     */
    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;
    }

Java String indexOf() 方法

菜鸟教程Java String indexOf() 方法实例

indexOf() 方法有以下四种形式:

public int indexOf(int ch): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。

中文翻译:

返回此字符串中第一次出现指定字符的索引。 如果值ch的字符出现在此String对象表示的字符序列中,则返回第一次出现的索引(以 Unicode 代码单元表示)。 对于 0 到 0xFFFF(含)范围内的ch值,这是满足以下条件的最小值k :
this.charAt(k) == ch

是真的。 对于ch其他值,它是满足以下条件的最小值k :
this.codePointAt(k) == ch

是真的。 在任一情况下,如果此字符串中没有出现此类字符,则返回-1 。
参数:
ch – 一个字符(Unicode 代码点)。
返回值:
此对象表示的字符序列中该字符第一次出现的索引,如果该字符没有出现,则为-1 。

/**
     * Returns the index within this string of the first occurrence of
     * the specified character. If a character with value
     * {@code ch} occurs in the character sequence represented by
     * this {@code String} object, then the index (in Unicode
     * code units) of the first such occurrence is returned. For
     * values of {@code ch} in the range from 0 to 0xFFFF
     * (inclusive), this is the smallest value <i>k</i> such that:
     * <blockquote><pre>
     * this.charAt(<i>k</i>) == ch
     * </pre></blockquote>
     * is true. For other values of {@code ch}, it is the
     * smallest value <i>k</i> such that:
     * <blockquote><pre>
     * this.codePointAt(<i>k</i>) == ch
     * </pre></blockquote>
     * is true. In either case, if no such character occurs in this
     * string, then {@code -1} is returned.
     *
     * @param   ch   a character (Unicode code point).
     * @return  the index of the first occurrence of the character in the
     *          character sequence represented by this object, or
     *          {@code -1} if the character does not occur.
     */
    public int indexOf(int ch) {
        return indexOf(ch, 0);
    }

public int indexOf(int ch, int fromIndex): 返回从 fromIndex 位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。

中文翻译:

返回此字符串中第一次出现指定字符的索引,从指定索引开始搜索。
如果值为ch的字符出现在此String对象表示的字符序列中,其索引不小于fromIndex ,则返回第一个此类出现的索引。 对于 0 到 0xFFFF(含)范围内的ch值,这是满足以下条件的最小值k :
(this.charAt(k) == ch) && (k >= fromIndex)

是真的。 对于ch其他值,它是满足以下条件的最小值k :
(this.codePointAt(k) == ch) && (k >= fromIndex)

是真的。 在任一情况下,如果此字符串中fromIndex位置或之后没有出现此类字符,则返回-1 。
fromIndex的值没有限制。 如果它是负数,它与它为零的效果相同:可以搜索整个字符串。 如果它大于此字符串的长度,则其效果与等于此字符串的长度相同:返回-1 。
所有索引均以char值(Unicode 代码单元)指定。
参数:
ch – 一个字符(Unicode 代码点)。
fromIndex – 开始搜索的索引。
返回值:
此对象表示的字符序列中该字符第一次出现的索引,该索引大于或等于fromIndex ,如果该字符没有出现,则为-1 。

/**
     * Returns the index within this string of the first occurrence of the
     * specified character, starting the search at the specified index.
     * <p>
     * If a character with value {@code ch} occurs in the
     * character sequence represented by this {@code String}
     * object at an index no smaller than {@code fromIndex}, then
     * the index of the first such occurrence is returned. For values
     * of {@code ch} in the range from 0 to 0xFFFF (inclusive),
     * this is the smallest value <i>k</i> such that:
     * <blockquote><pre>
     * (this.charAt(<i>k</i>) == ch) {@code &&} (<i>k</i> >= fromIndex)
     * </pre></blockquote>
     * is true. For other values of {@code ch}, it is the
     * smallest value <i>k</i> such that:
     * <blockquote><pre>
     * (this.codePointAt(<i>k</i>) == ch) {@code &&} (<i>k</i> >= fromIndex)
     * </pre></blockquote>
     * is true. In either case, if no such character occurs in this
     * string at or after position {@code fromIndex}, then
     * {@code -1} is returned.
     *
     * <p>
     * There is no restriction on the value of {@code fromIndex}. If it
     * is negative, it has the same effect as if it were zero: this entire
     * string may be searched. If it is greater than the length of this
     * string, it has the same effect as if it were equal to the length of
     * this string: {@code -1} is returned.
     *
     * <p>All indices are specified in {@code char} values
     * (Unicode code units).
     *
     * @param   ch          a character (Unicode code point).
     * @param   fromIndex   the index to start the search from.
     * @return  the index of the first occurrence of the character in the
     *          character sequence represented by this object that is greater
     *          than or equal to {@code fromIndex}, or {@code -1}
     *          if the character does not occur.
     */
    public int indexOf(int ch, int fromIndex) {
        final int max = value.length;
        if (fromIndex < 0) {
            fromIndex = 0;
        } else if (fromIndex >= max) {
            // Note: fromIndex might be near -1>>>1.
            return -1;
        }

        if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
            // handle most cases here (ch is a BMP code point or a
            // negative value (invalid code point))
            final char[] value = this.value;
            for (int i = fromIndex; i < max; i++) {
                if (value[i] == ch) {
                    return i;
                }
            }
            return -1;
        } else {
            return indexOfSupplementary(ch, fromIndex);
        }
    }

int indexOf(String str): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。

中文翻译:

返回此字符串中第一次出现指定子字符串的索引。
返回的索引是最小值k ,其中:
this.startsWith(str, k)

如果不存在这样的k值,则返回-1 。
参数:
str – 要搜索的子字符串。
返回值:
指定子字符串第一次出现的索引,如果没有这样的出现,则为-1 。

/**
     * Returns the index within this string of the first occurrence of the
     * specified substring.
     *
     * <p>The returned index is the smallest value <i>k</i> for which:
     * <blockquote><pre>
     * this.startsWith(str, <i>k</i>)
     * </pre></blockquote>
     * If no such value of <i>k</i> exists, then {@code -1} is returned.
     *
     * @param   str   the substring to search for.
     * @return  the index of the first occurrence of the specified substring,
     *          or {@code -1} if there is no such occurrence.
     */
    public int indexOf(String str) {
        return indexOf(str, 0);
    }

int indexOf(String str, int fromIndex): 返回从 fromIndex 位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。

中文翻译:
返回此字符串中第一次出现指定子字符串的索引,从指定索引开始。
返回的索引是最小值k ,其中:
k >= fromIndex && this.startsWith(str, k)

如果不存在这样的k值,则返回-1 。
参数:
str – 要搜索的子字符串。
fromIndex – 开始搜索的索引。
返回值:
指定子字符串第一次出现的索引,从指定索引开始,如果没有这样的出现,则为-1 。

/**
     * Returns the index within this string of the first occurrence of the
     * specified substring, starting at the specified index.
     *
     * <p>The returned index is the smallest value <i>k</i> for which:
     * <blockquote><pre>
     * <i>k</i> >= fromIndex {@code &&} this.startsWith(str, <i>k</i>)
     * </pre></blockquote>
     * If no such value of <i>k</i> exists, then {@code -1} is returned.
     *
     * @param   str         the substring to search for.
     * @param   fromIndex   the index from which to start the search.
     * @return  the index of the first occurrence of the specified substring,
     *          starting at the specified index,
     *          or {@code -1} if there is no such occurrence.
     */
    public int indexOf(String str, int fromIndex) {
        return indexOf(value, 0, value.length,
                str.value, 0, str.value.length, fromIndex);
    }

Java intern() 方法

intern() 方法返回字符串对象的规范化表示形式。

它遵循以下规则:对于任意两个字符串 s 和 t,当且仅当 s.equals(t) 为 true 时,s.intern() == t.intern() 才为 true。

菜鸟教程Java intern() 方法实例

中文翻译:

返回字符串对象的规范表示。
字符串池最初是空的,由String类私下维护。
当调用 intern 方法时,如果池中已经包含一个等于该String对象的字符串equals(Object)由equals(Object)方法确定equals(Object) ,则返回池中的字符串。 否则,将此String对象添加到池中并返回对此String对象的引用。
由此可见,对于任何两个字符串s和t , s.intern() == t.intern()是true当且仅当s.equals(t)是true 。
所有文字字符串和字符串值常量表达式都被实习。 字符串文字在The Java™ Language Specification 的第 3.10.5 节中定义。
返回值:
与此字符串具有相同内容的字符串,但保证来自唯一字符串池

/**
     * Returns a canonical representation for the string object.
     * <p>
     * A pool of strings, initially empty, is maintained privately by the
     * class {@code String}.
     * <p>
     * When the intern method is invoked, if the pool already contains a
     * string equal to this {@code String} object as determined by
     * the {@link #equals(Object)} method, then the string from the pool is
     * returned. Otherwise, this {@code String} object is added to the
     * pool and a reference to this {@code String} object is returned.
     * <p>
     * It follows that for any two strings {@code s} and {@code t},
     * {@code s.intern() == t.intern()} is {@code true}
     * if and only if {@code s.equals(t)} is {@code true}.
     * <p>
     * All literal strings and string-valued constant expressions are
     * interned. String literals are defined in section 3.10.5 of the
     * <cite>The Java™ Language Specification</cite>.
     *
     * @return  a string that has the same contents as this string, but is
     *          guaranteed to be from a pool of unique strings.
     */
    public native String intern();

Java lastIndexOf() 方法

菜鸟教程Java lastIndexOf() 方法实例

lastIndexOf() 方法有以下四种形式:

public int lastIndexOf(int ch): 返回指定字符在此字符串中最后一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。

中文翻译:

返回此字符串中最后一次出现的指定字符的索引。 对于 0 到 0xFFFF(含)范围内的ch值,返回的索引(以 Unicode 代码单元为单位)是最大值k ,使得:
this.charAt(k) == ch

是真的。 对于ch其他值,它是满足以下条件的最大值k :
this.codePointAt(k) == ch

是真的。 在任一情况下,如果此字符串中没有出现此类字符,则返回-1 。 从最后一个字符开始向后搜索String 。
参数:
ch – 一个字符(Unicode 代码点)。
返回值:
此对象表示的字符序列中该字符最后一次出现的索引,如果该字符未出现,则为-1 。

/**
     * Returns the index within this string of the last occurrence of
     * the specified character. For values of {@code ch} in the
     * range from 0 to 0xFFFF (inclusive), the index (in Unicode code
     * units) returned is the largest value <i>k</i> such that:
     * <blockquote><pre>
     * this.charAt(<i>k</i>) == ch
     * </pre></blockquote>
     * is true. For other values of {@code ch}, it is the
     * largest value <i>k</i> such that:
     * <blockquote><pre>
     * this.codePointAt(<i>k</i>) == ch
     * </pre></blockquote>
     * is true.  In either case, if no such character occurs in this
     * string, then {@code -1} is returned.  The
     * {@code String} is searched backwards starting at the last
     * character.
     *
     * @param   ch   a character (Unicode code point).
     * @return  the index of the last occurrence of the character in the
     *          character sequence represented by this object, or
     *          {@code -1} if the character does not occur.
     */
    public int lastIndexOf(int ch) {
        return lastIndexOf(ch, value.length - 1);
    }

public int lastIndexOf(int ch, int fromIndex): 返回指定字符在此字符串中最后一次出现处的索引,从指定的索引处开始进行反向搜索,如果此字符串中没有这样的字符,则返回 -1。

中文翻译:

返回此字符串中最后一次出现的指定字符的索引,从指定的索引开始向后搜索。 对于 0 到 0xFFFF(含)范围内的ch值,返回的索引是最大值k ,使得:
(this.charAt(k) == ch) && (k <= fromIndex)

是真的。 对于ch其他值,它是满足以下条件的最大值k :
(this.codePointAt(k) == ch) && (k <= fromIndex)

是真的。 在任一情况下,如果此字符串中的fromIndex位置或之前没有出现此类字符,则返回-1 。
所有索引均以char值(Unicode 代码单元)指定。
参数:
ch – 一个字符(Unicode 代码点)。
fromIndex – 开始搜索的索引。 fromIndex的值没有限制。 如果它大于或等于此字符串的长度,则其效果与等于此字符串长度少 1 的效果相同:可以搜索整个字符串。 如果它是负数,它与 -1 具有相同的效果:返回 -1。
返回值:
此对象表示的字符序列中该字符最后一次出现的索引,该索引小于或等于fromIndex ,如果该字符在该点之前未出现,则为-1 。

/**
     * Returns the index within this string of the last occurrence of
     * the specified character, searching backward starting at the
     * specified index. For values of {@code ch} in the range
     * from 0 to 0xFFFF (inclusive), the index returned is the largest
     * value <i>k</i> such that:
     * <blockquote><pre>
     * (this.charAt(<i>k</i>) == ch) {@code &&} (<i>k</i> <= fromIndex)
     * </pre></blockquote>
     * is true. For other values of {@code ch}, it is the
     * largest value <i>k</i> such that:
     * <blockquote><pre>
     * (this.codePointAt(<i>k</i>) == ch) {@code &&} (<i>k</i> <= fromIndex)
     * </pre></blockquote>
     * is true. In either case, if no such character occurs in this
     * string at or before position {@code fromIndex}, then
     * {@code -1} is returned.
     *
     * <p>All indices are specified in {@code char} values
     * (Unicode code units).
     *
     * @param   ch          a character (Unicode code point).
     * @param   fromIndex   the index to start the search from. There is no
     *          restriction on the value of {@code fromIndex}. If it is
     *          greater than or equal to the length of this string, it has
     *          the same effect as if it were equal to one less than the
     *          length of this string: this entire string may be searched.
     *          If it is negative, it has the same effect as if it were -1:
     *          -1 is returned.
     * @return  the index of the last occurrence of the character in the
     *          character sequence represented by this object that is less
     *          than or equal to {@code fromIndex}, or {@code -1}
     *          if the character does not occur before that point.
     */
    public int lastIndexOf(int ch, int fromIndex) {
        if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
            // handle most cases here (ch is a BMP code point or a
            // negative value (invalid code point))
            final char[] value = this.value;
            int i = Math.min(fromIndex, value.length - 1);
            for (; i >= 0; i--) {
                if (value[i] == ch) {
                    return i;
                }
            }
            return -1;
        } else {
            return lastIndexOfSupplementary(ch, fromIndex);
        }
    }

public int lastIndexOf(String str): 返回指定子字符串在此字符串中最右边出现处的索引,如果此字符串中没有这样的字符,则返回 -1。

中文翻译:

返回此字符串中最后一次出现的指定子字符串的索引。 空字符串 “” 的最后一次出现被认为出现在索引值this.length() 。
返回的索引是最大值k ,其中:
this.startsWith(str, k)

如果不存在这样的k值,则返回-1 。
参数:
str – 要搜索的子字符串。
返回值:
指定子字符串最后一次出现的索引,如果没有这样的出现,则为-1 。

/**
     * Returns the index within this string of the last occurrence of the
     * specified substring.  The last occurrence of the empty string ""
     * is considered to occur at the index value {@code this.length()}.
     *
     * <p>The returned index is the largest value <i>k</i> for which:
     * <blockquote><pre>
     * this.startsWith(str, <i>k</i>)
     * </pre></blockquote>
     * If no such value of <i>k</i> exists, then {@code -1} is returned.
     *
     * @param   str   the substring to search for.
     * @return  the index of the last occurrence of the specified substring,
     *          or {@code -1} if there is no such occurrence.
     */
    public int lastIndexOf(String str) {
        return lastIndexOf(str, value.length);
    }

public int lastIndexOf(String str, int fromIndex): 返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索,如果此字符串中没有这样的字符,则返回 -1。

中文翻译:
返回此字符串中最后一次出现的指定子字符串的索引,从指定索引开始向后搜索。
返回的索引是最大值k ,其中:
k <= fromIndex && this.startsWith(str, k)

如果不存在这样的k值,则返回-1 。
参数:
str – 要搜索的子字符串。
fromIndex – 开始搜索的索引。
返回值:
指定子字符串最后一次出现的索引,从指定索引向后搜索,如果没有这样的出现,则为-1 。

/**
     * Returns the index within this string of the last occurrence of the
     * specified substring, searching backward starting at the specified index.
     *
     * <p>The returned index is the largest value <i>k</i> for which:
     * <blockquote><pre>
     * <i>k</i> {@code <=} fromIndex {@code &&} this.startsWith(str, <i>k</i>)
     * </pre></blockquote>
     * If no such value of <i>k</i> exists, then {@code -1} is returned.
     *
     * @param   str         the substring to search for.
     * @param   fromIndex   the index to start the search from.
     * @return  the index of the last occurrence of the specified substring,
     *          searching backward from the specified index,
     *          or {@code -1} if there is no such occurrence.
     */
    public int lastIndexOf(String str, int fromIndex) {
        return lastIndexOf(value, 0, value.length,
                str.value, 0, str.value.length, fromIndex);
    }

Java String length() 方法

length() 方法用于返回字符串的长度。

空字符串的长度返回 0。

菜鸟教程Java String length() 方法实例

中文翻译:

返回此字符串的长度。 长度等于字符串中Unicode 代码单元的数量。

返回值:此对象表示的字符序列的长度。

/**
     * 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;
    }

Java matches() 方法

matches() 方法用于检测字符串是否匹配给定的正则表达式。

调用此方法的 str.matches(regex) 形式与以下表达式产生的结果完全相同:

Pattern.matches(regex, str)

regex – 匹配字符串的正则表达式。

菜鸟教程Java matches() 方法实例

中文翻译:

判断此字符串是否与给定的正则表达式匹配。
以str .matches( regex )形式调用此方法会产生与表达式完全相同的结果
Pattern 。 matches( regex , str )
参数:
regex – 与此字符串匹配的正则表达式
返回值:
true当且仅当此字符串给定的正则表达式匹配
顶:
PatternSyntaxException – 如果正则表达式的语法无效
自:
1.4
请参见:
Pattern

/**
     * Tells whether or not this string matches the given <a
     * href="../util/regex/Pattern.html#sum">regular expression</a>.
     *
     * <p> An invocation of this method of the form
     * <i>str</i>{@code .matches(}<i>regex</i>{@code )} yields exactly the
     * same result as the expression
     *
     * <blockquote>
     * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#matches(String,CharSequence)
     * matches(<i>regex</i>, <i>str</i>)}
     * </blockquote>
     *
     * @param   regex
     *          the regular expression to which this string is to be matched
     *
     * @return  {@code true} if, and only if, this string matches the
     *          given regular expression
     *
     * @throws  PatternSyntaxException
     *          if the regular expression's syntax is invalid
     *
     * @see java.util.regex.Pattern
     *
     * @since 1.4
     * @spec JSR-51
     */
    public boolean matches(String regex) {
        return Pattern.matches(regex, this);
    }

Pattern.matches(regex, str)介绍:
编译给定的正则表达式并尝试将给定的输入与其匹配。
调用这个方便的表单方法
Pattern.matches(regex, input);
行为方式与表达式完全相同
Pattern.compile(regex).matcher(input).matches()
如果一个模式要被多次使用,编译一次并重用它会比每次调用这个方法更有效率。
参数:
regex – 要编译的表达式
input – 要匹配的字符序列
返回值:
正则表达式是否与输入匹配
顶:
PatternSyntaxException – 如果表达式的语法无效

源码如下:

/**
     * Compiles the given regular expression and attempts to match the given
     * input against it.
     *
     * <p> An invocation of this convenience method of the form
     *
     * <blockquote><pre>
     * Pattern.matches(regex, input);</pre></blockquote>
     *
     * behaves in exactly the same way as the expression
     *
     * <blockquote><pre>
     * Pattern.compile(regex).matcher(input).matches()</pre></blockquote>
     *
     * <p> If a pattern is to be used multiple times, compiling it once and reusing
     * it will be more efficient than invoking this method each time.  </p>
     *
     * @param  regex
     *         The expression to be compiled
     *
     * @param  input
     *         The character sequence to be matched
     * @return whether or not the regular expression matches on the input
     * @throws  PatternSyntaxException
     *          If the expression's syntax is invalid
     */
    public static boolean matches(String regex, CharSequence input) {
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(input);
        return m.matches();
    }

Java regionMatches() 方法

regionMatches() 方法用于检测两个字符串在一个区域内是否相等。

菜鸟教程Java regionMatches() 方法实例

ignoreCase – 如果为 true,则比较字符时忽略大小写。
toffset – 此字符串中子区域的起始偏移量。
other – 字符串参数。
ooffset – 字符串参数中子区域的起始偏移量。
len – 要比较的字符数。

boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)

中文翻译:

测试两个字符串区域是否相等。
此String对象的子字符串与参数other的子字符串进行比较。 如果这些子字符串表示相同的字符序列,则结果为true ,当且仅当ignoreCase为真时忽略大小写。 要比较的此String对象的子String从索引toffset开始,长度为len 。 要比较的other的子串从索引ooffset开始,长度为len 。 当且仅当以下至少一项为真时,结果为false :
toffset为负。
ooffset为负。
toffset+len大于此String对象的长度。
ooffset+len大于另一个参数的长度。
ignoreCase为false并且存在一些小于len非负整数k使得:
this.charAt(toffset+k) != other.charAt(ooffset+k)

ignoreCase为true并且存在一些小于len非负整数k使得:
Character.toLowerCase(this.charAt(toffset+k)) !=
Character.toLowerCase(other.charAt(ooffset+k))

和:
Character.toUpperCase(this.charAt(toffset+k)) !=
Character.toUpperCase(other.charAt(ooffset+k))

参数:
ignoreCase – 如果为true ,则在比较字符时忽略大小写。
tooffset – 此字符串中子区域的起始偏移量。
其他 - 字符串参数。
ooffset – 字符串参数中子区域的起始偏移量。
len – 要比较的字符数。
返回值:
如果此字符串的指定子区域与字符串参数的指定子区域匹配,则为true ; 否则为false 。 匹配是精确匹配还是不区分大小写取决于ignoreCase参数。

/**
     * Tests if two string regions are equal.
     * <p>
     * A substring of this {@code String} object is compared to a substring
     * of the argument {@code other}. The result is {@code true} if these
     * substrings represent character sequences that are the same, ignoring
     * case if and only if {@code ignoreCase} is true. The substring of
     * this {@code String} object to be compared begins at index
     * {@code toffset} and has length {@code len}. The substring of
     * {@code other} to be compared begins at index {@code ooffset} and
     * has length {@code len}. The result is {@code false} if and only if
     * at least one of the following is true:
     * <ul><li>{@code toffset} is negative.
     * <li>{@code ooffset} is negative.
     * <li>{@code toffset+len} is greater than the length of this
     * {@code String} object.
     * <li>{@code ooffset+len} is greater than the length of the other
     * argument.
     * <li>{@code ignoreCase} is {@code false} and there is some nonnegative
     * integer <i>k</i> less than {@code len} such that:
     * <blockquote><pre>
     * this.charAt(toffset+k) != other.charAt(ooffset+k)
     * </pre></blockquote>
     * <li>{@code ignoreCase} is {@code true} and there is some nonnegative
     * integer <i>k</i> less than {@code len} such that:
     * <blockquote><pre>
     * Character.toLowerCase(this.charAt(toffset+k)) !=
     Character.toLowerCase(other.charAt(ooffset+k))
     * </pre></blockquote>
     * and:
     * <blockquote><pre>
     * Character.toUpperCase(this.charAt(toffset+k)) !=
     *         Character.toUpperCase(other.charAt(ooffset+k))
     * </pre></blockquote>
     * </ul>
     *
     * @param   ignoreCase   if {@code true}, ignore case when comparing
     *                       characters.
     * @param   toffset      the starting offset of the subregion in this
     *                       string.
     * @param   other        the string argument.
     * @param   ooffset      the starting offset of the subregion in the string
     *                       argument.
     * @param   len          the number of characters to compare.
     * @return  {@code true} if the specified subregion of this string
     *          matches the specified subregion of the string argument;
     *          {@code false} otherwise. Whether the matching is exact
     *          or case insensitive depends on the {@code ignoreCase}
     *          argument.
     */
    public boolean regionMatches(boolean ignoreCase, int toffset,
            String other, int ooffset, int len) {
        char ta[] = value;
        int to = toffset;
        char pa[] = other.value;
        int po = ooffset;
        // Note: toffset, ooffset, or len might be near -1>>>1.
        if ((ooffset < 0) || (toffset < 0)
                || (toffset > (long)value.length - len)
                || (ooffset > (long)other.value.length - len)) {
            return false;
        }
        while (len-- > 0) {
            char c1 = ta[to++];
            char c2 = pa[po++];
            if (c1 == c2) {
                continue;
            }
            if (ignoreCase) {
                // If characters don't match but case may be ignored,
                // try converting both characters to uppercase.
                // If the results match, then the comparison scan should
                // continue.
                char u1 = Character.toUpperCase(c1);
                char u2 = Character.toUpperCase(c2);
                if (u1 == u2) {
                    continue;
                }
                // Unfortunately, conversion to uppercase does not work properly
                // for the Georgian alphabet, which has strange rules about case
                // conversion.  So we need to make one last check before
                // exiting.
                if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) {
                    continue;
                }
            }
            return false;
        }
        return true;
    }

boolean regionMatches(int toffset, String other, int ooffset, int len)

中文翻译:

测试两个字符串区域是否相等。
此String对象的子字符串与参数 other 的子字符串进行比较。 如果这些子字符串表示相同的字符序列,则结果为真。 要比较的此String对象的子String从索引toffset开始,长度为len 。 要比较的 other 的子串从索引ooffset开始,长度为len 。 当且仅当以下至少一项为真时,结果为false :
toffset为负。
ooffset为负。
toffset+len大于此String对象的长度。
ooffset+len大于另一个参数的长度。
有一些小于len非负整数k使得: this.charAt(toffset + k ) != other.charAt(ooffset + k )
参数:
tooffset – 此字符串中子区域的起始偏移量。
其他 - 字符串参数。
ooffset – 字符串参数中子区域的起始偏移量。
len – 要比较的字符数。
返回值:
如果此字符串的指定子区域与字符串参数的指定子区域完全匹配,则为true ; 否则为false 。

/**
     * Tests if two string regions are equal.
     * <p>
     * A substring of this {@code String} object is compared to a substring
     * of the argument other. The result is true if these substrings
     * represent identical character sequences. The substring of this
     * {@code String} object to be compared begins at index {@code toffset}
     * and has length {@code len}. The substring of other to be compared
     * begins at index {@code ooffset} and has length {@code len}. The
     * result is {@code false} if and only if at least one of the following
     * is true:
     * <ul><li>{@code toffset} is negative.
     * <li>{@code ooffset} is negative.
     * <li>{@code toffset+len} is greater than the length of this
     * {@code String} object.
     * <li>{@code ooffset+len} is greater than the length of the other
     * argument.
     * <li>There is some nonnegative integer <i>k</i> less than {@code len}
     * such that:
     * {@code this.charAt(toffset + }<i>k</i>{@code ) != other.charAt(ooffset + }
     * <i>k</i>{@code )}
     * </ul>
     *
     * @param   toffset   the starting offset of the subregion in this string.
     * @param   other     the string argument.
     * @param   ooffset   the starting offset of the subregion in the string
     *                    argument.
     * @param   len       the number of characters to compare.
     * @return  {@code true} if the specified subregion of this string
     *          exactly matches the specified subregion of the string argument;
     *          {@code false} otherwise.
     */
    public boolean regionMatches(int toffset, String other, int ooffset,
            int len) {
        char ta[] = value;
        int to = toffset;
        char pa[] = other.value;
        int po = ooffset;
        // Note: toffset, ooffset, or len might be near -1>>>1.
        if ((ooffset < 0) || (toffset < 0)
                || (toffset > (long)value.length - len)
                || (ooffset > (long)other.value.length - len)) {
            return false;
        }
        while (len-- > 0) {
            if (ta[to++] != pa[po++]) {
                return false;
            }
        }
        return true;
    }

Java replace() 方法

replace() 方法通过用 newChar 字符替换字符串中出现的所有 searchChar 字符,并返回替换后的新字符串。

菜鸟教程Java replace() 方法实例

中文翻译:

返回一个字符串,该字符串是用newChar替换此字符串中所有出现的oldChar 。
如果字符oldChar没有出现在此String对象表示的字符序列中,则返回对此String对象的引用。 否则,将返回一个String对象,该对象表示与此String对象表示的字符序列相同的字符序列,但每次出现的oldChar都会被出现的newChar 。
例子:
“mesquite in your cellar”.replace(‘e’, ‘o’)
returns “mosquito in your collar”
“the war of baronets”.replace(‘r’, ‘y’)
returns “the way of bayonets”
“sparring with a purple porpoise”.replace(‘p’, ‘t’)
returns “starring with a turtle tortoise”
“JonL”.replace(‘q’, ‘x’) returns “JonL” (no change)

参数:
oldChar – 旧字符。
newChar – 新字符。
返回值:
通过用newChar替换每次出现的oldChar从此字符串派生的字符串。

/**
     * Returns a string resulting from replacing all occurrences of
     * {@code oldChar} in this string with {@code newChar}.
     * <p>
     * If the character {@code oldChar} does not occur in the
     * character sequence represented by this {@code String} object,
     * then a reference to this {@code String} object is returned.
     * Otherwise, a {@code String} object is returned that
     * represents a character sequence identical to the character sequence
     * represented by this {@code String} object, except that every
     * occurrence of {@code oldChar} is replaced by an occurrence
     * of {@code newChar}.
     * <p>
     * Examples:
     * <blockquote><pre>
     * "mesquite in your cellar".replace('e', 'o')
     *         returns "mosquito in your collar"
     * "the war of baronets".replace('r', 'y')
     *         returns "the way of bayonets"
     * "sparring with a purple porpoise".replace('p', 't')
     *         returns "starring with a turtle tortoise"
     * "JonL".replace('q', 'x') returns "JonL" (no change)
     * </pre></blockquote>
     *
     * @param   oldChar   the old character.
     * @param   newChar   the new character.
     * @return  a string derived from this string by replacing every
     *          occurrence of {@code oldChar} with {@code newChar}.
     */
    public String replace(char oldChar, char newChar) {
        if (oldChar != newChar) {
            int len = value.length;
            int i = -1;
            char[] val = value; /* avoid getfield opcode */

            while (++i < len) {
                if (val[i] == oldChar) {
                    break;
                }
            }
            if (i < len) {
                char buf[] = new char[len];
                for (int j = 0; j < i; j++) {
                    buf[j] = val[j];
                }
                while (i < len) {
                    char c = val[i];
                    buf[i] = (c == oldChar) ? newChar : c;
                    i++;
                }
                return new String(buf, true);
            }
        }
        return this;
    }

Java replaceAll() 方法

replaceAll() 方法使用给定的参数 replacement 替换字符串所有匹配给定的正则表达式的子字符串。

菜鸟教程Java replaceAll() 方法实例

中文翻译:

用给定的替换替换此字符串中与给定正则表达式匹配的每个子字符串。
以str .replaceAll( regex , repl )形式调用此方法会产生与表达式完全相同的结果
Pattern . compile ( regex ). matcher ( str ). replaceAll ( repl )
请注意,替换字符串中的反斜杠 ( \ ) 和美元符号 ( $ ) 可能会导致结果与将其视为文字替换字符串时的结果不同; 见Matcher.replaceAll 。 如果需要,使用Matcher.quoteReplacement抑制这些字符的特殊含义。
参数:
regex – 与此字符串匹配的正则表达式
替换 - 要替换每个匹配项的字符串
返回值:
结果String
顶:
PatternSyntaxException – 如果正则表达式的语法无效
自:
1.4
请参见:
Pattern

/**
     * Replaces each substring of this string that matches the given <a
     * href="../util/regex/Pattern.html#sum">regular expression</a> with the
     * given replacement.
     *
     * <p> An invocation of this method of the form
     * <i>str</i>{@code .replaceAll(}<i>regex</i>{@code ,} <i>repl</i>{@code )}
     * yields exactly the same result as the expression
     *
     * <blockquote>
     * <code>
     * {@link java.util.regex.Pattern}.{@link
     * java.util.regex.Pattern#compile compile}(<i>regex</i>).{@link
     * java.util.regex.Pattern#matcher(java.lang.CharSequence) matcher}(<i>str</i>).{@link
     * java.util.regex.Matcher#replaceAll replaceAll}(<i>repl</i>)
     * </code>
     * </blockquote>
     *
     *<p>
     * Note that backslashes ({@code \}) and dollar signs ({@code $}) in the
     * replacement string may cause the results to be different than if it were
     * being treated as a literal replacement string; see
     * {@link java.util.regex.Matcher#replaceAll Matcher.replaceAll}.
     * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
     * meaning of these characters, if desired.
     *
     * @param   regex
     *          the regular expression to which this string is to be matched
     * @param   replacement
     *          the string to be substituted for each match
     *
     * @return  The resulting {@code String}
     *
     * @throws  PatternSyntaxException
     *          if the regular expression's syntax is invalid
     *
     * @see java.util.regex.Pattern
     *
     * @since 1.4
     * @spec JSR-51
     */
    public String replaceAll(String regex, String replacement) {
        return Pattern.compile(regex).matcher(this).replaceAll(replacement);
    }

Java replaceFirst() 方法

replaceFirst() 方法使用给定的参数 replacement 替换字符串第一个匹配给定的正则表达式的子字符串。

菜鸟教程Java replaceFirst() 方法实例

中文翻译:

用给定的替换替换此字符串的第一个与给定正则表达式匹配的子字符串。
以str .replaceFirst( regex , repl )形式调用此方法会产生与表达式完全相同的结果
Pattern . compile ( regex ). matcher ( str ). replaceFirst ( repl )
请注意,替换字符串中的反斜杠 ( \ ) 和美元符号 ( $ ) 可能会导致结果与将其视为文字替换字符串时的结果不同; 见Matcher.replaceFirst 。 如果需要,使用Matcher.quoteReplacement抑制这些字符的特殊含义。
参数:
regex – 与此字符串匹配的正则表达式
替换 - 要替换第一个匹配项的字符串
返回值:
结果String
顶:
PatternSyntaxException – 如果正则表达式的语法无效
自:
1.4
请参见:
Pattern

/**
     * Replaces the first substring of this string that matches the given <a
     * href="../util/regex/Pattern.html#sum">regular expression</a> with the
     * given replacement.
     *
     * <p> An invocation of this method of the form
     * <i>str</i>{@code .replaceFirst(}<i>regex</i>{@code ,} <i>repl</i>{@code )}
     * yields exactly the same result as the expression
     *
     * <blockquote>
     * <code>
     * {@link java.util.regex.Pattern}.{@link
     * java.util.regex.Pattern#compile compile}(<i>regex</i>).{@link
     * java.util.regex.Pattern#matcher(java.lang.CharSequence) matcher}(<i>str</i>).{@link
     * java.util.regex.Matcher#replaceFirst replaceFirst}(<i>repl</i>)
     * </code>
     * </blockquote>
     *
     *<p>
     * Note that backslashes ({@code \}) and dollar signs ({@code $}) in the
     * replacement string may cause the results to be different than if it were
     * being treated as a literal replacement string; see
     * {@link java.util.regex.Matcher#replaceFirst}.
     * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
     * meaning of these characters, if desired.
     *
     * @param   regex
     *          the regular expression to which this string is to be matched
     * @param   replacement
     *          the string to be substituted for the first match
     *
     * @return  The resulting {@code String}
     *
     * @throws  PatternSyntaxException
     *          if the regular expression's syntax is invalid
     *
     * @see java.util.regex.Pattern
     *
     * @since 1.4
     * @spec JSR-51
     */
    public String replaceFirst(String regex, String replacement) {
        return Pattern.compile(regex).matcher(this).replaceFirst(replacement);
    }

Java split() 方法

split() 方法根据匹配给定的正则表达式来拆分字符串。

菜鸟教程Java split() 方法实例

String[] split(String regex):根据给定正则表达式的匹配拆分此字符串。

中文翻译:

围绕给定正则表达式的匹配拆分此字符串。
此方法的工作方式就像通过使用给定表达式和零限制参数调用双参数split方法一样。 因此,结果数组中不包含尾随空字符串。
例如,字符串"boo:and:foo"使用这些表达式产生以下结果:
正则表达式
结果

{ “boo”, “and”, “foo” }

{ “b”, “”, “:and:f” }
参数:
regex – 定界正则表达式
返回值:
通过围绕给定正则表达式的匹配拆分此字符串计算出的字符串数组
顶:
PatternSyntaxException – 如果正则表达式的语法无效
自:
1.4
请参见:
Pattern

/**
     * Splits this string around matches of the given <a
     * href="../util/regex/Pattern.html#sum">regular expression</a>.
     *
     * <p> This method works as if by invoking the two-argument {@link
     * #split(String, int) split} method with the given expression and a limit
     * argument of zero.  Trailing empty strings are therefore not included in
     * the resulting array.
     *
     * <p> The string {@code "boo:and:foo"}, for example, yields the following
     * results with these expressions:
     *
     * <blockquote><table cellpadding=1 cellspacing=0 summary="Split examples showing regex and result">
     * <tr>
     *  <th>Regex</th>
     *  <th>Result</th>
     * </tr>
     * <tr><td align=center>:</td>
     *     <td>{@code { "boo", "and", "foo" }}</td></tr>
     * <tr><td align=center>o</td>
     *     <td>{@code { "b", "", ":and:f" }}</td></tr>
     * </table></blockquote>
     *
     *
     * @param  regex
     *         the delimiting regular expression
     *
     * @return  the array of strings computed by splitting this string
     *          around matches of the given regular expression
     *
     * @throws  PatternSyntaxException
     *          if the regular expression's syntax is invalid
     *
     * @see java.util.regex.Pattern
     *
     * @since 1.4
     * @spec JSR-51
     */
    public String[] split(String regex) {
        return split(regex, 0);
    }

String[] split(String regex, int limit):根据匹配给定的正则表达式来拆分此字符串。

中文翻译:

围绕给定正则表达式的匹配拆分此字符串。
此方法返回的数组包含此字符串的每个子字符串,这些子字符串由与给定表达式匹配的另一个子字符串终止或由字符串的末尾终止。 数组中的子字符串按它们在此字符串中出现的顺序排列。 如果表达式不匹配输入的任何部分,则结果数组只有一个元素,即这个字符串。
如果此字符串的开头存在正宽度匹配,则结果数组的开头将包含一个空的前导子字符串。 然而,开头的零宽度匹配永远不会产生这样的空前导子串。
limit参数控制应用模式的次数,因此会影响结果数组的长度。 如果限制n大于零,则该模式将最多应用n - 1 次,数组的长度将不大于n ,并且数组的最后一个条目将包含最后一个匹配的分隔符之外的所有输入。 如果n为非正数,则该模式将被应用尽可能多的次数,并且数组可以具有任意长度。 如果n为零,则该模式将被应用尽可能多的次数,数组可以具有任意长度,并且将丢弃尾随的空字符串。
例如,字符串"boo:and:foo"使用这些参数产生以下结果:
正则表达式
限制
结果

:
 2
 { “boo”, “and:foo” }
 :
 5
 { “boo”, “and”, “foo” }
 :
 -2
 { “boo”, “and”, “foo” }
 ○
 5
 { “b”, “”, “:and:f”, “”, “” }
 ○
 -2
 { “b”, “”, “:and:f”, “”, “” }
 ○
 0
 { “b”, “”, “:and:f” }


以str形式调用此方法。 split( regex , n )产生与表达式相同的结果
Pattern . compile ( regex ). split ( str , n )
参数:
regex – 定界正则表达式
limit – 结果阈值,如上所述
返回值:
通过围绕给定正则表达式的匹配拆分此字符串计算出的字符串数组
顶:
PatternSyntaxException – 如果正则表达式的语法无效
自:
1.4
请参见:
Pattern

/**
     * Splits this string around matches of the given
     * <a href="../util/regex/Pattern.html#sum">regular expression</a>.
     *
     * <p> The array returned by this method contains each substring of this
     * string that is terminated by another substring that matches the given
     * expression or is terminated by the end of the string.  The substrings in
     * the array are in the order in which they occur in this string.  If the
     * expression does not match any part of the input then the resulting array
     * has just one element, namely this string.
     *
     * <p> When there is a positive-width match at the beginning of this
     * string then an empty leading substring is included at the beginning
     * of the resulting array. A zero-width match at the beginning however
     * never produces such empty leading substring.
     *
     * <p> The {@code limit} parameter controls the number of times the
     * pattern is applied and therefore affects the length of the resulting
     * array.  If the limit <i>n</i> is greater than zero then the pattern
     * will be applied at most <i>n</i> - 1 times, the array's
     * length will be no greater than <i>n</i>, and the array's last entry
     * will contain all input beyond the last matched delimiter.  If <i>n</i>
     * is non-positive then the pattern will be applied as many times as
     * possible and the array can have any length.  If <i>n</i> is zero then
     * the pattern will be applied as many times as possible, the array can
     * have any length, and trailing empty strings will be discarded.
     *
     * <p> The string {@code "boo:and:foo"}, for example, yields the
     * following results with these parameters:
     *
     * <blockquote><table cellpadding=1 cellspacing=0 summary="Split example showing regex, limit, and result">
     * <tr>
     *     <th>Regex</th>
     *     <th>Limit</th>
     *     <th>Result</th>
     * </tr>
     * <tr><td align=center>:</td>
     *     <td align=center>2</td>
     *     <td>{@code { "boo", "and:foo" }}</td></tr>
     * <tr><td align=center>:</td>
     *     <td align=center>5</td>
     *     <td>{@code { "boo", "and", "foo" }}</td></tr>
     * <tr><td align=center>:</td>
     *     <td align=center>-2</td>
     *     <td>{@code { "boo", "and", "foo" }}</td></tr>
     * <tr><td align=center>o</td>
     *     <td align=center>5</td>
     *     <td>{@code { "b", "", ":and:f", "", "" }}</td></tr>
     * <tr><td align=center>o</td>
     *     <td align=center>-2</td>
     *     <td>{@code { "b", "", ":and:f", "", "" }}</td></tr>
     * <tr><td align=center>o</td>
     *     <td align=center>0</td>
     *     <td>{@code { "b", "", ":and:f" }}</td></tr>
     * </table></blockquote>
     *
     * <p> An invocation of this method of the form
     * <i>str.</i>{@code split(}<i>regex</i>{@code ,} <i>n</i>{@code )}
     * yields the same result as the expression
     *
     * <blockquote>
     * <code>
     * {@link java.util.regex.Pattern}.{@link
     * java.util.regex.Pattern#compile compile}(<i>regex</i>).{@link
     * java.util.regex.Pattern#split(java.lang.CharSequence,int) split}(<i>str</i>, <i>n</i>)
     * </code>
     * </blockquote>
     *
     *
     * @param  regex
     *         the delimiting regular expression
     *
     * @param  limit
     *         the result threshold, as described above
     *
     * @return  the array of strings computed by splitting this string
     *          around matches of the given regular expression
     *
     * @throws  PatternSyntaxException
     *          if the regular expression's syntax is invalid
     *
     * @see java.util.regex.Pattern
     *
     * @since 1.4
     * @spec JSR-51
     */
    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);
    }

Java startsWith() 方法

startsWith() 方法用于检测字符串是否以指定的前缀开始。

菜鸟教程Java startsWith() 方法实例

boolean startsWith(String prefix):测试此字符串是否以指定的前缀开始。

中文翻译:

测试此字符串是否以指定的前缀开头。
参数:
前缀 - 前缀。
返回值:
如果参数所表示的字符序列是该字符串所表示的字符序列的前缀,则为true ; 否则为false 。 另请注意,如果参数是空字符串或等于由equals(Object)方法确定的此String对象,则将返回true 。
自:

  1. 0
/**
     * Tests if this string starts with the specified prefix.
     *
     * @param   prefix   the prefix.
     * @return  {@code true} if the character sequence represented by the
     *          argument is a prefix of the character sequence represented by
     *          this string; {@code false} otherwise.
     *          Note also that {@code true} will be returned if the
     *          argument is an empty string or is equal to this
     *          {@code String} object as determined by the
     *          {@link #equals(Object)} method.
     * @since   1. 0
     */
    public boolean startsWith(String prefix) {
        return startsWith(prefix, 0);
    }

boolean startsWith(String prefix, int toffset):测试此字符串从指定索引开始的子字符串是否以指定前缀开始。

中文翻译:

测试此字符串的从指定索引开始的子字符串是否以指定前缀开头。
参数:
前缀 - 前缀。
toffset – 从哪里开始在这个字符串中查找。
返回值:
如果参数表示的字符序列是此对象的子字符串的前缀,则为true , toffset索引toffset开始; 否则为false 。 如果toffset为负或大于此String对象的长度,则结果为false ; 否则结果与表达式的结果相同
this.substring(toffset).startsWith(prefix)

/**
     * Tests if the substring of this string beginning at the
     * specified index starts with the specified prefix.
     *
     * @param   prefix    the prefix.
     * @param   toffset   where to begin looking in this string.
     * @return  {@code true} if the character sequence represented by the
     *          argument is a prefix of the substring of this object starting
     *          at index {@code toffset}; {@code false} otherwise.
     *          The result is {@code false} if {@code toffset} is
     *          negative or greater than the length of this
     *          {@code String} object; otherwise the result is the same
     *          as the result of the expression
     *          <pre>
     *          this.substring(toffset).startsWith(prefix)
     *          </pre>
     */
    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;
    }

Java subSequence() 方法

subSequence() 方法返回一个新的字符序列,它是此序列的一个子序列。

菜鸟教程Java subSequence() 方法实例

中文翻译:

返回作为此序列子序列的字符序列。
对表单的此方法的调用
str.subSequence(begin, end)
行为方式与调用完全相同
str.substring(begin, end)
参数:
beginIndex – 开始索引,包括在内。
endIndex – 结束索引,独占。
返回值:
指定的子序列。
顶:
IndexOutOfBoundsException – 如果beginIndex或endIndex为负,如果endIndex大于length() ,或者如果beginIndex大于endIndex
接口说明:
定义此方法以便String类可以实现CharSequence接口。
自:
1.4

/**
     * Returns a character sequence that is a subsequence of this sequence.
     *
     * <p> An invocation of this method of the form
     *
     * <blockquote><pre>
     * str.subSequence(begin, end)</pre></blockquote>
     *
     * behaves in exactly the same way as the invocation
     *
     * <blockquote><pre>
     * str.substring(begin, end)</pre></blockquote>
     *
     * @apiNote
     * This method is defined so that the {@code String} class can implement
     * the {@link CharSequence} interface.
     *
     * @param   beginIndex   the begin index, inclusive.
     * @param   endIndex     the end index, exclusive.
     * @return  the specified subsequence.
     *
     * @throws  IndexOutOfBoundsException
     *          if {@code beginIndex} or {@code endIndex} is negative,
     *          if {@code endIndex} is greater than {@code length()},
     *          or if {@code beginIndex} is greater than {@code endIndex}
     *
     * @since 1.4
     * @spec JSR-51
     */
    public CharSequence subSequence(int beginIndex, int endIndex) {
        return this.substring(beginIndex, endIndex);
    }

Java toCharArray() 方法

toCharArray() 方法将字符串转换为字符数组。

菜鸟教程Java toCharArray() 方法实例

中文翻译:

将此字符串转换为新的字符数组。
返回值:一个新分配的字符数组,其长度是这个字符串的长度,其内容被初始化为包含这个字符串所代表的字符序列。

/**
     * Converts this string to a new character array.
     *
     * @return  a newly allocated character array whose length is the length
     *          of this string and whose contents are initialized to contain
     *          the character sequence represented by this string.
     */
    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;
    }

Java toLowerCase() 方法

toLowerCase() 方法将字符串转换为小写。

菜鸟教程Java toLowerCase() 方法实例

中文翻译:

使用默认语言环境的规则将此String所有字符转换为小写。 这相当于调用toLowerCase(Locale.getDefault()) 。
注意:此方法对区域设置敏感,如果用于旨在独立解释区域设置的字符串,可能会产生意外结果。 示例是编程语言标识符、协议密钥和 HTML 标签。 例如,土耳其语语言环境中的"TITLE".toLowerCase()返回"t\u0131tle" ,其中 ‘\u0131’ 是拉丁文小写字母 DOTLESS I 字符。 要获得对区域设置不敏感的字符串的正确结果,请使用toLowerCase(Locale.ROOT) 。

返回值:
String ,转换为小写。
请参见:
toLowerCase(Locale)

/**
     * Converts all of the characters in this {@code String} to lower
     * case using the rules of the default locale. This is equivalent to calling
     * {@code toLowerCase(Locale.getDefault())}.
     * <p>
     * <b>Note:</b> This method is locale sensitive, and may produce unexpected
     * results if used for strings that are intended to be interpreted locale
     * independently.
     * Examples are programming language identifiers, protocol keys, and HTML
     * tags.
     * For instance, {@code "TITLE".toLowerCase()} in a Turkish locale
     * returns {@code "t\u005Cu0131tle"}, where '\u005Cu0131' is the
     * LATIN SMALL LETTER DOTLESS I character.
     * To obtain correct results for locale insensitive strings, use
     * {@code toLowerCase(Locale.ROOT)}.
     * <p>
     * @return  the {@code String}, converted to lowercase.
     * @see     java.lang.String#toLowerCase(Locale)
     */
    public String toLowerCase() {
        return toLowerCase(Locale.getDefault());
    }

此代码借助于public String toLowerCase(Locale locale)

中文翻译:

使用给定Locale的规则将此String所有字符转换为小写。 大小写映射基于Character类指定的 Unicode 标准版本。 由于大小写映射并不总是 1:1 字符映射,因此生成的String可能与原始String长度不同。
下表是小写映射的示例:
地区语言代码
大写
小写
描述
tr(土耳其语)
\u0130
\u0069
上面带点的大写字母 I -> 小写字母 i
tr(土耳其语)
\u0049
\u0131
大写字母 I -> 小写字母无点 i
(全部)
炸薯条
炸薯条
小写字符串中的所有字符
(全部)

小写字符串中的所有字符
参数:
语言环境 – 使用此语言环境的大小写转换规则
返回值:
String ,转换为小写。
自:
1.1
请参见:
toLowerCase() , toUpperCase() , toUpperCase(Locale)

源码如下(此代码就在public String toLowerCase()之前):

/**
     * Converts all of the characters in this {@code String} to lower
     * case using the rules of the given {@code Locale}.  Case mapping is based
     * on the Unicode Standard version specified by the {@link java.lang.Character Character}
     * class. Since case mappings are not always 1:1 char mappings, the resulting
     * {@code String} may be a different length than the original {@code String}.
     * <p>
     * Examples of lowercase  mappings are in the following table:
     * <table border="1" summary="Lowercase mapping examples showing language code of locale, upper case, lower case, and description">
     * <tr>
     *   <th>Language Code of Locale</th>
     *   <th>Upper Case</th>
     *   <th>Lower Case</th>
     *   <th>Description</th>
     * </tr>
     * <tr>
     *   <td>tr (Turkish)</td>
     *   <td>\u0130</td>
     *   <td>\u0069</td>
     *   <td>capital letter I with dot above -> small letter i</td>
     * </tr>
     * <tr>
     *   <td>tr (Turkish)</td>
     *   <td>\u0049</td>
     *   <td>\u0131</td>
     *   <td>capital letter I -> small letter dotless i </td>
     * </tr>
     * <tr>
     *   <td>(all)</td>
     *   <td>French Fries</td>
     *   <td>french fries</td>
     *   <td>lowercased all chars in String</td>
     * </tr>
     * <tr>
     *   <td>(all)</td>
     *   <td><img src="doc-files/capiota.gif" alt="capiota"><img src="doc-files/capchi.gif" alt="capchi">
     *       <img src="doc-files/captheta.gif" alt="captheta"><img src="doc-files/capupsil.gif" alt="capupsil">
     *       <img src="doc-files/capsigma.gif" alt="capsigma"></td>
     *   <td><img src="doc-files/iota.gif" alt="iota"><img src="doc-files/chi.gif" alt="chi">
     *       <img src="doc-files/theta.gif" alt="theta"><img src="doc-files/upsilon.gif" alt="upsilon">
     *       <img src="doc-files/sigma1.gif" alt="sigma"></td>
     *   <td>lowercased all chars in String</td>
     * </tr>
     * </table>
     *
     * @param locale use the case transformation rules for this locale
     * @return the {@code String}, converted to lowercase.
     * @see     java.lang.String#toLowerCase()
     * @see     java.lang.String#toUpperCase()
     * @see     java.lang.String#toUpperCase(Locale)
     * @since   1.1
     */
    public String toLowerCase(Locale locale) {
        if (locale == null) {
            throw new NullPointerException();
        }

        int firstUpper;
        final int len = value.length;

        /* Now check if there are any characters that need to be changed. */
        scan: {
            for (firstUpper = 0 ; firstUpper < len; ) {
                char c = value[firstUpper];
                if ((c >= Character.MIN_HIGH_SURROGATE)
                        && (c <= Character.MAX_HIGH_SURROGATE)) {
                    int supplChar = codePointAt(firstUpper);
                    if (supplChar != Character.toLowerCase(supplChar)) {
                        break scan;
                    }
                    firstUpper += Character.charCount(supplChar);
                } else {
                    if (c != Character.toLowerCase(c)) {
                        break scan;
                    }
                    firstUpper++;
                }
            }
            return this;
        }

        char[] result = new char[len];
        int resultOffset = 0;  /* result may grow, so i+resultOffset
                                * is the write location in result */

        /* Just copy the first few lowerCase characters. */
        System.arraycopy(value, 0, result, 0, firstUpper);

        String lang = locale.getLanguage();
        boolean localeDependent =
                (lang == "tr" || lang == "az" || lang == "lt");
        char[] lowerCharArray;
        int lowerChar;
        int srcChar;
        int srcCount;
        for (int i = firstUpper; i < len; i += srcCount) {
            srcChar = (int)value[i];
            if ((char)srcChar >= Character.MIN_HIGH_SURROGATE
                    && (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
                srcChar = codePointAt(i);
                srcCount = Character.charCount(srcChar);
            } else {
                srcCount = 1;
            }
            if (localeDependent ||
                srcChar == '\u03A3' || // GREEK CAPITAL LETTER SIGMA
                srcChar == '\u0130') { // LATIN CAPITAL LETTER I WITH DOT ABOVE
                lowerChar = ConditionalSpecialCasing.toLowerCaseEx(this, i, locale);
            } else {
                lowerChar = Character.toLowerCase(srcChar);
            }
            if ((lowerChar == Character.ERROR)
                    || (lowerChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
                if (lowerChar == Character.ERROR) {
                    lowerCharArray =
                            ConditionalSpecialCasing.toLowerCaseCharArray(this, i, locale);
                } else if (srcCount == 2) {
                    resultOffset += Character.toChars(lowerChar, result, i + resultOffset) - srcCount;
                    continue;
                } else {
                    lowerCharArray = Character.toChars(lowerChar);
                }

                /* Grow result if needed */
                int mapLen = lowerCharArray.length;
                if (mapLen > srcCount) {
                    char[] result2 = new char[result.length + mapLen - srcCount];
                    System.arraycopy(result, 0, result2, 0, i + resultOffset);
                    result = result2;
                }
                for (int x = 0; x < mapLen; ++x) {
                    result[i + resultOffset + x] = lowerCharArray[x];
                }
                resultOffset += (mapLen - srcCount);
            } else {
                result[i + resultOffset] = (char)lowerChar;
            }
        }
        return new String(result, 0, len + resultOffset);
    }

Java toString() 方法

toString() 方法返回此对象本身(它已经是一个字符串)。

菜鸟教程Java toString() 方法实例

中文翻译:

这个对象(它已经是一个字符串!)本身被返回。
返回值:字符串本身。

/**
     * This object (which is already a string!) is itself returned.
     *
     * @return  the string itself.
     */
    public String toString() {
        return this;
    }

注意:此代码重写了object类的toString方法。

Java toUpperCase() 方法

toUpperCase() 方法将字符串小写字符转换为大写。

菜鸟教程Java toUpperCase() 方法实例

中文翻译:

使用默认语言环境的规则将此String所有字符转换为大写。 此方法等效于toUpperCase(Locale.getDefault()) 。
注意:此方法对区域设置敏感,如果用于旨在独立解释区域设置的字符串,可能会产生意外结果。 示例是编程语言标识符、协议密钥和 HTML 标签。 例如,土耳其语语言环境中的"title".toUpperCase()返回"T\u0130TLE" ,其中 ‘\u0130’ 是拉丁文大写字母 I 和 DOT ABOVE 字符。 要获得对区域设置不敏感的字符串的正确结果,请使用toUpperCase(Locale.ROOT) 。

返回值:
String ,转换为大写。
请参见:
toUpperCase(Locale)

/**
     * Converts all of the characters in this {@code String} to upper
     * case using the rules of the default locale. This method is equivalent to
     * {@code toUpperCase(Locale.getDefault())}.
     * <p>
     * <b>Note:</b> This method is locale sensitive, and may produce unexpected
     * results if used for strings that are intended to be interpreted locale
     * independently.
     * Examples are programming language identifiers, protocol keys, and HTML
     * tags.
     * For instance, {@code "title".toUpperCase()} in a Turkish locale
     * returns {@code "T\u005Cu0130TLE"}, where '\u005Cu0130' is the
     * LATIN CAPITAL LETTER I WITH DOT ABOVE character.
     * To obtain correct results for locale insensitive strings, use
     * {@code toUpperCase(Locale.ROOT)}.
     * <p>
     * @return  the {@code String}, converted to uppercase.
     * @see     java.lang.String#toUpperCase(Locale)
     */
    public String toUpperCase() {
        return toUpperCase(Locale.getDefault());
    }

此代码借助于public String toUpperCase(Locale locale)

中文翻译:
使用给定Locale的规则将此String所有字符转换为大写。 大小写映射基于Character类指定的 Unicode 标准版本。 由于大小写映射并不总是 1:1 字符映射,因此生成的String可能与原始String长度不同。
区域敏感和 1:M 大小写映射的示例在下表中。
地区语言代码
小写
大写
描述
tr(土耳其语)
\u0069
\u0130
小写字母 i -> 大写字母 I 上面有点
tr(土耳其语)
\u0131
\u0049
小写无点 i -> 大写字母 I
(全部)
\u00df
\u0053 \u0053
小写字母尖 s -> 两个字母:SS
(全部)
法尔格努根
FAHRVERGNÜGEN

参数:
语言环境 – 使用此语言环境的大小写转换规则
返回值:
String ,转换为大写。
自:
1.1
请参见:
toUpperCase() , toLowerCase() , toLowerCase(Locale)

源码如下(此代码就在public String toUpperCase()之前):

/**
     * Converts all of the characters in this {@code String} to upper
     * case using the rules of the given {@code Locale}. Case mapping is based
     * on the Unicode Standard version specified by the {@link java.lang.Character Character}
     * class. Since case mappings are not always 1:1 char mappings, the resulting
     * {@code String} may be a different length than the original {@code String}.
     * <p>
     * Examples of locale-sensitive and 1:M case mappings are in the following table.
     *
     * <table border="1" summary="Examples of locale-sensitive and 1:M case mappings. Shows Language code of locale, lower case, upper case, and description.">
     * <tr>
     *   <th>Language Code of Locale</th>
     *   <th>Lower Case</th>
     *   <th>Upper Case</th>
     *   <th>Description</th>
     * </tr>
     * <tr>
     *   <td>tr (Turkish)</td>
     *   <td>\u0069</td>
     *   <td>\u0130</td>
     *   <td>small letter i -> capital letter I with dot above</td>
     * </tr>
     * <tr>
     *   <td>tr (Turkish)</td>
     *   <td>\u0131</td>
     *   <td>\u0049</td>
     *   <td>small letter dotless i -> capital letter I</td>
     * </tr>
     * <tr>
     *   <td>(all)</td>
     *   <td>\u00df</td>
     *   <td>\u0053 \u0053</td>
     *   <td>small letter sharp s -> two letters: SS</td>
     * </tr>
     * <tr>
     *   <td>(all)</td>
     *   <td>Fahrvergnügen</td>
     *   <td>FAHRVERGNÜGEN</td>
     *   <td></td>
     * </tr>
     * </table>
     * @param locale use the case transformation rules for this locale
     * @return the {@code String}, converted to uppercase.
     * @see     java.lang.String#toUpperCase()
     * @see     java.lang.String#toLowerCase()
     * @see     java.lang.String#toLowerCase(Locale)
     * @since   1.1
     */
    public String toUpperCase(Locale locale) {
        if (locale == null) {
            throw new NullPointerException();
        }

        int firstLower;
        final int len = value.length;

        /* Now check if there are any characters that need to be changed. */
        scan: {
            for (firstLower = 0 ; firstLower < len; ) {
                int c = (int)value[firstLower];
                int srcCount;
                if ((c >= Character.MIN_HIGH_SURROGATE)
                        && (c <= Character.MAX_HIGH_SURROGATE)) {
                    c = codePointAt(firstLower);
                    srcCount = Character.charCount(c);
                } else {
                    srcCount = 1;
                }
                int upperCaseChar = Character.toUpperCaseEx(c);
                if ((upperCaseChar == Character.ERROR)
                        || (c != upperCaseChar)) {
                    break scan;
                }
                firstLower += srcCount;
            }
            return this;
        }

        /* result may grow, so i+resultOffset is the write location in result */
        int resultOffset = 0;
        char[] result = new char[len]; /* may grow */

        /* Just copy the first few upperCase characters. */
        System.arraycopy(value, 0, result, 0, firstLower);

        String lang = locale.getLanguage();
        boolean localeDependent =
                (lang == "tr" || lang == "az" || lang == "lt");
        char[] upperCharArray;
        int upperChar;
        int srcChar;
        int srcCount;
        for (int i = firstLower; i < len; i += srcCount) {
            srcChar = (int)value[i];
            if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
                (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
                srcChar = codePointAt(i);
                srcCount = Character.charCount(srcChar);
            } else {
                srcCount = 1;
            }
            if (localeDependent) {
                upperChar = ConditionalSpecialCasing.toUpperCaseEx(this, i, locale);
            } else {
                upperChar = Character.toUpperCaseEx(srcChar);
            }
            if ((upperChar == Character.ERROR)
                    || (upperChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
                if (upperChar == Character.ERROR) {
                    if (localeDependent) {
                        upperCharArray =
                                ConditionalSpecialCasing.toUpperCaseCharArray(this, i, locale);
                    } else {
                        upperCharArray = Character.toUpperCaseCharArray(srcChar);
                    }
                } else if (srcCount == 2) {
                    resultOffset += Character.toChars(upperChar, result, i + resultOffset) - srcCount;
                    continue;
                } else {
                    upperCharArray = Character.toChars(upperChar);
                }

                /* Grow result if needed */
                int mapLen = upperCharArray.length;
                if (mapLen > srcCount) {
                    char[] result2 = new char[result.length + mapLen - srcCount];
                    System.arraycopy(result, 0, result2, 0, i + resultOffset);
                    result = result2;
                }
                for (int x = 0; x < mapLen; ++x) {
                    result[i + resultOffset + x] = upperCharArray[x];
                }
                resultOffset += (mapLen - srcCount);
            } else {
                result[i + resultOffset] = (char)upperChar;
            }
        }
        return new String(result, 0, len + resultOffset);
    }

Java trim() 方法

trim() 方法用于删除字符串的头尾空白符。

菜鸟教程Java trim() 方法实例

中文翻译:

返回一个字符串,其值为该字符串,删除任何前导和尾随空格。
如果该String对象表示一个空字符序列,或由该代表字符序列的第一个和最后一个字符String对象都具有大于代码’\u0020’ (空格字符),则此参考String返回对象。
否则,如果字符串中没有代码大于’\u0020’的字符,则返回表示空字符串的String对象。
否则,让k是代码大于’\u0020’的字符串中第一个字符的索引,让m是代码大于’\u0020’的字符串中最后一个字符的索引。 返回一个String对象,表示此字符串的子字符串,以索引k处的字符开头,以索引m处的字符结尾 - 即this.substring(k, m + 1) 。
此方法可用于从字符串的开头和结尾修剪空格(如上定义)。
返回值:
一个字符串,其值为这个字符串,删除了任何前导和尾随空格,或者这个字符串,如果它没有前导或尾随空格。

/**
     * Returns a string whose value is this string, with any leading and trailing
     * whitespace removed.
     * <p>
     * If this {@code String} object represents an empty character
     * sequence, or the first and last characters of character sequence
     * represented by this {@code String} object both have codes
     * greater than {@code '\u005Cu0020'} (the space character), then a
     * reference to this {@code String} object is returned.
     * <p>
     * Otherwise, if there is no character with a code greater than
     * {@code '\u005Cu0020'} in the string, then a
     * {@code String} object representing an empty string is
     * returned.
     * <p>
     * Otherwise, let <i>k</i> be the index of the first character in the
     * string whose code is greater than {@code '\u005Cu0020'}, and let
     * <i>m</i> be the index of the last character in the string whose code
     * is greater than {@code '\u005Cu0020'}. A {@code String}
     * object is returned, representing the substring of this string that
     * begins with the character at index <i>k</i> and ends with the
     * character at index <i>m</i>-that is, the result of
     * {@code this.substring(k, m + 1)}.
     * <p>
     * This method may be used to trim whitespace (as defined above) from
     * the beginning and end of a string.
     *
     * @return  A string whose value is this string, with any leading and trailing white
     *          space removed, or this string if it has no leading or
     *          trailing white space.
     */
    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;
    }

Java valueOf() 方法

static String valueOf(primitive data type x):返回给定data type类型x参数的字符串表示形式。

valueOf() 方法有以下几种不同形式:

valueOf(boolean b): 返回 boolean 参数的字符串表示形式。.

valueOf(char c): 返回 char 参数的字符串表示形式。

valueOf(char[] data): 返回 char 数组参数的字符串表示形式。

valueOf(char[] data, int offset, int count): 返回 char
数组参数的特定子数组的字符串表示形式。

valueOf(double d): 返回 double 参数的字符串表示形式。

valueOf(float f): 返回 float 参数的字符串表示形式。

valueOf(int i): 返回 int 参数的字符串表示形式。

valueOf(long l): 返回 long 参数的字符串表示形式。

valueOf(Object obj): 返回 Object 参数的字符串表示形式。

菜鸟教程Java valueOf() 方法实例

/**
     * Returns the string representation of the {@code Object} argument.
     *
     * @param   obj   an {@code Object}.
     * @return  if the argument is {@code null}, then a string equal to
     *          {@code "null"}; otherwise, the value of
     *          {@code obj.toString()} is returned.
     * @see     java.lang.Object#toString()
     */
    public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }

    /**
     * Returns the string representation of the {@code char} array
     * argument. The contents of the character array are copied; subsequent
     * modification of the character array does not affect the returned
     * string.
     *
     * @param   data     the character array.
     * @return  a {@code String} that contains the characters of the
     *          character array.
     */
    public static String valueOf(char data[]) {
        return new String(data);
    }

    /**
     * Returns the string representation of a specific subarray of the
     * {@code char} array argument.
     * <p>
     * The {@code offset} argument is the index of the first
     * character of the subarray. The {@code count} argument
     * specifies the length of the subarray. The contents of the subarray
     * are copied; subsequent modification of the character array does not
     * affect the returned string.
     *
     * @param   data     the character array.
     * @param   offset   initial offset of the subarray.
     * @param   count    length of the subarray.
     * @return  a {@code String} that contains the characters of the
     *          specified subarray of the character array.
     * @exception IndexOutOfBoundsException if {@code offset} is
     *          negative, or {@code count} is negative, or
     *          {@code offset+count} is larger than
     *          {@code data.length}.
     */
    public static String valueOf(char data[], int offset, int count) {
        return new String(data, offset, count);
    }

    /**
     * Equivalent to {@link #valueOf(char[], int, int)}.
     *
     * @param   data     the character array.
     * @param   offset   initial offset of the subarray.
     * @param   count    length of the subarray.
     * @return  a {@code String} that contains the characters of the
     *          specified subarray of the character array.
     * @exception IndexOutOfBoundsException if {@code offset} is
     *          negative, or {@code count} is negative, or
     *          {@code offset+count} is larger than
     *          {@code data.length}.
     */
    public static String copyValueOf(char data[], int offset, int count) {
        return new String(data, offset, count);
    }

    /**
     * Equivalent to {@link #valueOf(char[])}.
     *
     * @param   data   the character array.
     * @return  a {@code String} that contains the characters of the
     *          character array.
     */
    public static String copyValueOf(char data[]) {
        return new String(data);
    }

    /**
     * Returns the string representation of the {@code boolean} argument.
     *
     * @param   b   a {@code boolean}.
     * @return  if the argument is {@code true}, a string equal to
     *          {@code "true"} is returned; otherwise, a string equal to
     *          {@code "false"} is returned.
     */
    public static String valueOf(boolean b) {
        return b ? "true" : "false";
    }

    /**
     * Returns the string representation of the {@code char}
     * argument.
     *
     * @param   c   a {@code char}.
     * @return  a string of length {@code 1} containing
     *          as its single character the argument {@code c}.
     */
    public static String valueOf(char c) {
        char data[] = {c};
        return new String(data, true);
    }

    /**
     * Returns the string representation of the {@code int} argument.
     * <p>
     * The representation is exactly the one returned by the
     * {@code Integer.toString} method of one argument.
     *
     * @param   i   an {@code int}.
     * @return  a string representation of the {@code int} argument.
     * @see     java.lang.Integer#toString(int, int)
     */
    public static String valueOf(int i) {
        return Integer.toString(i);
    }

    /**
     * Returns the string representation of the {@code long} argument.
     * <p>
     * The representation is exactly the one returned by the
     * {@code Long.toString} method of one argument.
     *
     * @param   l   a {@code long}.
     * @return  a string representation of the {@code long} argument.
     * @see     java.lang.Long#toString(long)
     */
    public static String valueOf(long l) {
        return Long.toString(l);
    }

    /**
     * Returns the string representation of the {@code float} argument.
     * <p>
     * The representation is exactly the one returned by the
     * {@code Float.toString} method of one argument.
     *
     * @param   f   a {@code float}.
     * @return  a string representation of the {@code float} argument.
     * @see     java.lang.Float#toString(float)
     */
    public static String valueOf(float f) {
        return Float.toString(f);
    }

    /**
     * Returns the string representation of the {@code double} argument.
     * <p>
     * The representation is exactly the one returned by the
     * {@code Double.toString} method of one argument.
     *
     * @param   d   a {@code double}.
     * @return  a  string representation of the {@code double} argument.
     * @see     java.lang.Double#toString(double)
     */
    public static String valueOf(double d) {
        return Double.toString(d);
    }

Java String contains() 方法

contains() 方法用于判断字符串中是否包含指定的字符或字符串。

菜鸟教程Java String contains() 方法实例

中文翻译:

当且仅当此字符串包含指定的 char 值序列时才返回 true。
参数:s - 要搜索的序列

/**
     * Returns true if and only if this string contains the specified
     * sequence of char values.
     *
     * @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;
    }

Java String isEmpty() 方法

isEmpty() 方法用于判断字符串是否为空。

菜鸟教程Java String isEmpty() 方法实例

中文翻译:

当且仅当length()为0返回true 。
返回值:如果length()为0则为true ,否则为false
自:1.6

/**
     * Returns {@code true} if, and only if, {@link #length()} is {@code 0}.
     *
     * @return {@code true} if {@link #length()} is {@code 0}, otherwise
     * {@code false}
     *
     * @since 1.6
     */
    public boolean isEmpty() {
        return value.length == 0;
    }