Module  java.base
Software package  java.lang

Class String

  • All implemented interfaces
    Serializable , CharSequence , Comparable<String>

    public final class String
    extends Object
    implements Serializable, Comparable<String>, CharSequence
    StringThe class represents strings. All string literals in Java programs (e.g."abc") are all implemented as instances of this class.

    Strings are immutable; Their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable, they can be shared. For example:

         String str = "abc";
     

    Equivalent to:

         char data[] = {'a', 'b', 'c'};
         String str = new String(data);
     

    Here are some examples of how to use strings:

         System.out.println("abc");
         String cde = "cde";
         System.out.println("abc" + cde);
         String c = "abc".substring(2,3);
         String d = cde.substring(1, 2);
     

    ClassStringincludingused forCheckssequenceofeachcharacters,used forCompare strings,used forSearchThe string,used formention取子StringAndused forCreateHasBy翻translateisbigwriteorsmallwriteofAllCharacterthe stringof副bookmethod of。 case mapping based onCharacterThe version of the Unicode standard specified by the class.

    The Java language provides special support for the string concatenation operator (+), and for conversion of other objects to strings. For further information on string concatenation and conversion, seeJava Language Specification 。

    Unless otherwise specified, it willnullparameter passed tonullthe constructor or method in ... will cause ... to be thrown.NullPointerException 。

    firstStringrepresented, wheresupplementary characterbysurrogate pairthe string represented in UTF-16 format (see SectionUnicode Character RepresentationsInCharacterto get more information, see the class). index values refer tocharcode units, so supplementary characters inStringuses two positions.

    StringThe class provides methods for handling Unicode code points (i.e., characters), and for handling Unicode code units (i.e.,charvalue) method.

    Unless otherwise noted, methods that compare strings do not take locale into account. CollatorThe class provides finer-grained, locale-sensitive String comparison methods.

    Implementation Note:
    as long as the compiler ultimately conforms tothe Java Language Specification, the implementation of the string concatenation operator is determined by the Java compiler. For example,javacthe compiler may implement operatorsStringBuffer , StringBuilder, orjava.lang.invoke.StringConcatFactorydepending on the JDK version. The implementation of string conversion is usually through a methodtoString, byObjectDefined by and inherited by all classes in Java.
    Starting from the following version:
    1.0
    See also:
    Object.toString() , StringBuffer , StringBuilder , Charset , Serialized Form
    See The Java™ Language Specification:
    15.18.1 String Concatenation Operator +
    • Constructor Summary

      Constructor  
      Constructor Description
      String()
      initializes the newly createdStringobject, making it represent an empty character sequence.
      String​(byte[] bytes)
      Constructs a new String by decoding the specified byte array using the platform's default charset.String 。
      String​(byte[] ascii, int hibyte)
      deprecated.
      This method cannot correctly convert bytes to characters.
      String​(byte[] bytes, int offset, int length)
      Constructs a new ... by decoding the specified byte subarray using the platform's default charset.String 。
      String​(byte[] ascii, int hibyte, int offset, int count)
      deprecated.
      This method cannot correctly convert bytes to characters.
      String​(byte[] bytes, int offset, int length, String charsetName)
      By decoding the specified byte subarray using the specified charsetStringconstructs a newString 。
      String​(byte[] bytes, int offset, int length, Charset charset)
      by using the specifiedcharsetDecodes the specified byte subStringconstructs a newString 。
      String​(byte[] bytes, String charsetName)
      constructs a newStringDecodes the specified array of bytes using the specifiedcharset 。
      String​(byte[] bytes, Charset charset)
      constructs a newStringDecodes the specified array of bytes using the specifiedcharset 。
      String​(char[] value)
      allocates a newString, so that it represents the character sequence currently contained in the character array parameter.
      String​(char[] value, int offset, int count)
      allocates a newStringwhich contains characters from a subarray of the character array argument.
      String​(int[] codePoints, int offset, int count)
      allocates a newString, which containsUnicode code pointcharacters in a subarray of the array argument.
      String​(String original)
      initializes the newly createdStringObject, so that it represents the same character sequence as the parameter; In other words, the newly created string is a copy of the argument string.
      String​(StringBuffer buffer)
      Allocates a new string that contains the sequence of characters currently contained in the string buffer argument.
      String​(StringBuilder builder)
      Allocates a new string that contains the sequence of characters currently contained in the string builder argument.
    • Method Summary

      All methods  Static method  Instance Methods Specific Methods  Deprecated Methods 
      Variables and types Methods Description
      char charAt​(int index)
      Returns the character at the specified indexcharvalue.
      IntStream chars()
      returnintthe stream, from this sequencecharvalue zero-extended.
      int codePointAt​(int index)
      Returns the character (Unicode code point) at the specified index.
      int codePointBefore​(int index)
      Returns the character (Unicode code point) before the specified index.
      int codePointCount​(int beginIndex, int endIndex)
      Return thisStringthe number of Unicode code points in the specified text range.
      IntStream codePoints()
      Returns a stream of code point values from this sequence.
      int compareTo​(String anotherString)
      Compares two strings lexicographically.
      int compareToIgnoreCase​(String str)
      Compares two strings lexicographically, ignoring case differences.
      String concat​(String str)
      Concatenates the specified string to the end of this string.
      boolean contains​(CharSequence s)
      Returns true if and only if this string contains the specified sequence of char values.
      boolean contentEquals​(CharSequence cs)
      this string with the specifiedCharSequence 。
      boolean contentEquals​(StringBuffer sb)
      this string with the specifiedStringBuffer 。
      static String copyValueOf​(char[] data)
      Equivalent tovalueOf(char[]) 。
      static String copyValueOf​(char[] data, int offset, int count)
      Equivalent tovalueOf(char[], int, int) 。
      boolean endsWith​(String suffix)
      Tests whether this string ends with the specified suffix.
      boolean equals​(Object anObject)
      Compares this string to the specified object.
      boolean equalsIgnoreCase​(String anotherString)
      Put thisStringwith anotherStringCompares, ignoring case.
      static String format​(String format, Object... args)
      Returns a formatted string using the specified format string and arguments.
      static String format​(Locale l, String format, Object... args)
      Returns a formatted string using the specified locale, format string, and arguments.
      byte[] getBytes()
      Using the platform's default charset, thisStringEncodes the string into a sequence of bytes, storing the result into a new byte array.
      void getBytes​(int srcBegin, int srcEnd, byte[] dst, int dstBegin)
      deprecated.
      This method cannot correctly convert characters to bytes.
      byte[] getBytes​(String charsetName)
      Using the named charset, thisStringEncodes the string into a sequence of bytes, storing the result into a new byte array.
      byte[] getBytes​(Charset charset)
      Uses the givencharsetPut thisStringEncodes the string into a sequence of bytes, storing the result into a new byte array.
      void getChars​(int srcBegin, int srcEnd, char[] dst, int dstBegin)
      Copies characters from this string into the destination character array.
      int hashCode()
      Returns the hash code for this string.
      int indexOf​(int ch)
      Returns the index within this string of the first occurrence of the specified character.
      int indexOf​(int ch, int fromIndex)
      Returns the index in this string of the first occurrence of the specified character, searching from the specified index.
      int indexOf​(String str)
      Returns the index within the string of the first occurrence of the specified substring.
      int indexOf​(String str, int fromIndex)
      Returns the index within the string of the first occurrence of the specified substring, starting at the specified index.
      String intern()
      Returns the canonical representation of the string object.
      boolean isBlank()
      If the string is empty or contains onlywhite spacecode point, then returnstrue, otherwisefalse 。
      boolean isEmpty()
      returntrue, if and only if,length()Yes0 。
      static String join​(CharSequence delimiter, CharSequence... elements)
      returned byCharSequence elementsa new String composed of a copy that is identical to the specifieddelimiterthe copies are joined together.
      static String join​(CharSequence delimiter, Iterable<? extends CharSequence> elements)
      returned byStringthe new one composed of copies ofString, whereCharSequence elementsspecifieddelimitera copy of.
      int lastIndexOf​(int ch)
      Returns the index within this string of the last occurrence of the specified character.
      int lastIndexOf​(int ch, int fromIndex)
      Returns the index within the string of the last occurrence of the specified character, searching backward from the specified index.
      int lastIndexOf​(String str)
      Returns the index within the string of the last occurrence of the specified substring.
      int lastIndexOf​(String str, int fromIndex)
      Returns the index within the string of the last occurrence of the specified substring, searching backward from the specified index.
      int length()
      Returns the length of this string.
      Stream<String> lines()
      Returns a stream of lines extracted from this string, separated by line terminators.
      boolean matches​(String regex)
      Determines whether this string is equal to the givenregular expressionmatch.
      int offsetByCodePoints​(int index, int codePointOffset)
      Return thisStringthe index in, which starts from the givenindexOffsetcodePointOffsetcode point.
      boolean regionMatches​(boolean ignoreCase, int toffset, String other, int ooffset, int len)
      Tests whether two string regions are equal.
      boolean regionMatches​(int toffset, String other, int ooffset, int len)
      Tests whether two string regions are equal.
      String repeat​(int count)
      Returns a string whose value is the concatenation of this string repeated.countTimes.
      String replace​(char oldChar, char newChar)
      Returns a string resulting from replacing all occurrencesoldCharin this stringnewChar 。
      String replace​(CharSequence target, CharSequence replacement)
      Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
      String replaceAll​(String regex, String replacement)
      Replace the given ... with the given ...regular expressionReplaces each substring of this string that matches.
      String replaceFirst​(String regex, String replacement)
      Replace the given ... with the given ...regular expressionReplaces the first substring of this string that matches.
      String[] split​(String regex)
      Splits this string around the givenof a regular expressionmatchitem 。
      String[] split​(String regex, int limit)
      Splits this string around the givenof a regular expressionmatchitem 。
      boolean startsWith​(String prefix)
      Tests whether this string starts with the specified prefix.
      boolean startsWith​(String prefix, int toffset)
      Tests whether the substring of this string beginning at the specified index starts with the specified prefix.
      String strip()
      Returns a string whose value is this string, with all leading and trailing whitespace removed.white space 。
      String stripLeading()
      Returns a string whose value is this string, with all leading whitespace removed.white space 。
      String stripTrailing()
      Returns a string whose value is this string, with all trailing whitespace removed.white space 。
      CharSequence subSequence​(int beginIndex, int endIndex)
      Returns a character sequence that is a subsequence of this sequence.
      String substring​(int beginIndex)
      Returns a string that is a substring of this string.
      String substring​(int beginIndex, int endIndex)
      Returns a string that is a substring of this string.
      char[] toCharArray()
      Converts this string to a new character array.
      String toLowerCase()
      Using the rules of the default locale, thisStringAll characters are converted to lowercase.
      String toLowerCase​(Locale locale)
      using the givenLocalerules of thisStringall characters converted toLocale 。
      String toString()
      This object (which is already a string!)
      String toUpperCase()
      Using the rules of the default locale, thisStringAll characters are converted to uppercase.
      String toUpperCase​(Locale locale)
      using the givenLocalerules of thisStringAll characters are converted to uppercase.
      String trim()
      Returns a string whose value is this string, with all leading and trailing spaces removed, where space is defined as having a code point less than or equal to'U+0020'any character (space character).
      static String valueOf​(boolean b)
      returnbooleanThe string representation of the argument.
      static String valueOf​(char c)
      returncharThe string representation of the argument.
      static String valueOf​(char[] data)
      returncharthe string representation of the array argument.
      static String valueOf​(char[] data, int offset, int count)
      returncharThe string representation of a specific subarray of the array argument.
      static String valueOf​(double d)
      returndoubleThe string representation of the argument.
      static String valueOf​(float f)
      returnfloatThe string representation of the argument.
      static String valueOf​(int i)
      returnintThe string representation of the argument.
      static String valueOf​(long l)
      returnlongThe string representation of the argument.
      static String valueOf​(Object obj)
      returnObjectThe string representation of the argument.
    • Field Details

      • CASE_INSENSITIVE_ORDER

        public static final Comparator<String> CASE_INSENSITIVE_ORDER
        bycompareToIgnoreCaseOrderStringcomparison of objectscompareToIgnoreCase 。 This comparator is serializable.

        Note that this comparatorWill notIt takes the locale into account and may lead to unsatisfactory ordering in some locales. CollatorThe class provides locale-sensitive comparison.

        Starting from the following version:
        1.2
        See also:
        Collator
    • Constructor Details

      • String

        public String()
        initializes the newly createdStringobject, making it represent an empty character sequence. Note that because strings are immutable, it is not necessary to use this constructor.
      • String

        public String​(String original)
        initializes the newly createdStringObject, so that it represents the same character sequence as the parameter; In other words, the newly created string is a copy of the argument string. unless requiredoriginalan explicit copy oforiginalThere is no need to use this constructor, because strings are immutable.
        Parameter
        original - A String
      • String

        public String​(char[] value)
        allocates a newString, so that it represents the character sequence currently contained in the character array parameter. Copies the contents of the character array; Subsequent modifications to the character array do not affect the newly created string.
        Parameter
        valueThe initial value of the string
      • String

        public String​(char[] value,
                      int offset,
                      int count)
        allocates a newStringwhich contains characters from a subarray of the character array argument. offsetthe argument is a subcountthe index of the first character,countparameter specifies a subcountthe length of. The contents of the subarray are copied; Subsequent modifications to the character array do not affect the newly created string.
        Parameter
        valueAn array used as a source of characters
        offset- initial offset
        count- length
        Exception
        IndexOutOfBoundsException- ifoffsetis negative, thencountis negative, oroffsetis greater thanvalue.length - count
      • String

        public String​(int[] codePoints,
                      int offset,
                      int count)
        allocates a newString, which containsUnicode code pointcharacters in a subarray of the array argument. offsetthe argument is a subcountthe index of the first code point,countparameter specifies a subcountthe length of. the contents of the subarray are converted tochar s; subsequent modificationsintThe array does not affect the newly created string.
        Parameter
        codePoints- the array to be used as a Unicode code point source
        offset- initial offset
        count- length
        Exception
        IllegalArgumentException- if incodePoints- if any invalid Unicode code point is found
        IndexOutOfBoundsException- ifoffsetis negative, thencountis negative, oroffsetis greater thancodePoints.length - count
        Starting from the following version:
        1.5
      • String

        public String​(byte[] bytes,
                      int offset,
                      int length,
                      String charsetName)
               throws UnsupportedEncodingException
        By decoding the specified byte subarray using the specified charsetStringconstructs a newString 。 NewStringThe length is a function of the charset, and therefore may not equal the length of the subarray.

        The behavior of this constructor is unspecified when the given byte is invalid in the given charset. When more control over the decoding process is required, useCharsetDecoderclass.

        Parameter
        bytesThe bytes to be decoded into characters
        offsetThe index of the first byte to be decoded
        lengthThe number of bytes to be decoded
        charsetName- supportedcharsetname of
        Exception
        UnsupportedEncodingExceptionIf the specified character set is not supported
        IndexOutOfBoundsException- ifoffsetis negative,lengthis negative, oroffsetis greater thanbytes.length - length
        Starting from the following version:
        1.1
      • String

        public String​(byte[] bytes,
                      int offset,
                      int length,
                      Charset charset)
        constructs a newStringBy decoding the specified byte subarray using the specifiedcharset 。 NewStringThe length is a function of the character set, and therefore may not be equal to the subStringthe length of.

        This method always uses this charset's default replacement string to replace malformed input and unmappable character sequences. When more control over the decoding process is required, useCharsetDecoderclass.

        Parameter
        bytesThe bytes to be decoded into characters
        offsetThe index of the first byte to be decoded
        lengthThe number of bytes to be decoded
        charset-Thecharsetis used to decodebytes
        Exception
        IndexOutOfBoundsException- ifoffsetis negative,lengthis negative, oroffsetis greater thanbytes.length - length
        Starting from the following version:
        1.6
      • String

        public String​(byte[] bytes,
                      String charsetName)
               throws UnsupportedEncodingException
        constructs a newStringDecodes the specified array of bytes using the specifiedcharset 。 NewStringThe length is a function of the charset, and therefore may not be equal to the length of the byte array.

        The behavior of this constructor is unspecified when the given byte is invalid in the given charset. When more control over the decoding process is required, useCharsetDecoderclass.

        Parameter
        bytesThe bytes to be decoded into characters
        charsetName- supportedcharsetname of
        Exception
        UnsupportedEncodingExceptionIf the specified character set is not supported
        Starting from the following version:
        1.1
      • String

        public String​(byte[] bytes,
                      Charset charset)
        constructs a newStringDecodes the specified array of bytes using the specifiedcharset 。 NewStringThe length is a function of the charset, and therefore may not be equal to the length of the byte array.

        This method always uses this charset's default replacement string to replace malformed input and unmappable character sequences. When more control over the decoding process is required, useCharsetDecoderclass.

        Parameter
        bytesThe bytes to be decoded into characters
        charset-Thecharsetis used to decodebytes
        Starting from the following version:
        1.6
      • String

        public String​(byte[] bytes,
                      int offset,
                      int length)
        Constructs a new ... by decoding the specified byte subarray using the platform's default charset.String 。 NewStringThe length is a function of the character set, and therefore may not be equal to the subStringthe length of.

        The behavior of this constructor when the given bytes are not valid in the default charset is unspecified. When more control over the decoding process is required, useCharsetDecoderclass.

        Parameter
        bytesThe bytes to be decoded into characters
        offsetThe index of the first byte to be decoded
        lengthThe number of bytes to be decoded
        Exception
        IndexOutOfBoundsException- ifoffsetis negative, thenlengthis negative, oroffsetis greater thanbytes.length - length
        Starting from the following version:
        1.1
      • String

        public String​(byte[] bytes)
        Constructs a new one by decoding the specified byte array using the platform's default charset.String 。 NewStringThe length is a function of the charset, and therefore may not be equal to the length of the byte array.

        The behavior of this constructor when the given bytes are not valid in the default charset is unspecified. When more control over the decoding process is required, useCharsetDecoderclass.

        Parameter
        bytesThe bytes to be decoded into characters
        Starting from the following version:
        1.1
      • String

        public String​(StringBuffer buffer)
        Allocates a new string that contains the sequence of characters currently contained in the string buffer argument. Copies the contents of the string buffer; Subsequent modification of the string buffer does not affect the newly created string.
        Parameter
        buffer - A StringBuffer
      • String

        public String​(StringBuilder builder)
        Allocates a new string that contains the sequence of characters currently contained in the string builder argument. The contents of the string builder are copied; Subsequent modification of the string builder does not affect the newly created string.

        This constructor is provided to facilitate migration toStringBuilder 。 ThroughtoStringThe method for obtaining a string from the string builder may run faster and is generally preferred.

        Parameter
        builder - A StringBuilder
        Starting from the following version:
        1.5
    • Method Details

      • length

        public int length()
        Returns the length of this string. the length is equal to that in the stringUnicode code unitsthe number of.
        Specified by:
        lengthIn the interfaceCharSequence
        Result
        The length of the character sequence represented by this object.
      • isEmpty

        public boolean isEmpty()
        returntrue, if and only if,length()Yes0 。
        Result
        trueiflength()Yes0, otherwisefalse
        Starting from the following version:
        1.6
      • charAt

        public char charAt​(int index)
        Returns the character at the specified indexcharvalue. the exponent range is0Tolength() - 1 。 the first of the sequencecharvalue at index0, the next is at index1, and so on, just like array indices.

        ifcharThe value specified by the index issurrogatethen the substitute value is returned.

        Specified by:
        charAtIn the interfaceCharSequence
        Parameter
        index - charthe index of the value.
        Result
        at the specified index of this stringcharvalue. firstcharvalue at index0 。
        Exception
        IndexOutOfBoundsException- ifindexif the index argument is negative or not less than the length of this string.
      • codePointAt

        public int codePointAt​(int index)
        Returns the character (Unicode code point) at the specified index. index referencecharvalue (Unicode code units), ranging from0tolength() - 1 。

        If the specified at the given indexcharIf the value is in the high surrogate range, then the following index is less than thisStringthe length, and at the following indexcharIf the value is in the low-surrogate range, then the supplementary code point corresponding to this surrogate pair is returned. Otherwise, return the one at the given indexcharvalue.

        Parameter
        index - charthe index of the value
        Result
        indexThe code point value of the character at the specified index
        Exception
        IndexOutOfBoundsException- ifindexif the index argument is negative or not less than the length of this string.
        Starting from the following version:
        1.5
      • codePointBefore

        public int codePointBefore​(int index)
        Returns the character (Unicode code point) before the specified index. index referencecharvalue (Unicode code units), ranging from1tolength 。

        ifcharAt value(index - 1)is in the low surrogate range,(index - 2)is not negative, andcharAt value(index - 2)is in the high surrogate range, then the supplementary code point value of the surrogate pair is returned. ifcharValue isindex - 1If it is an unpaired low surrogate or high surrogate, the surrogate value is returned.

        Parameter
        indexThe index following the code point to be returned
        Result
        the Unicode code point value before the given index.
        Exception
        IndexOutOfBoundsException- ifindexif the index argument is less than 1 or greater than the length of this string.
        Starting from the following version:
        1.5
      • codePointCount

        public int codePointCount​(int beginIndex,
                                  int endIndex)
        Return thisStringthe number of Unicode code points in the specified text range. The text range from the specifiedbeginIndexstarts at and extends tochar, the index number isendIndex - 1 。 Therefore, the length of the text range (incharin s) isendIndex-beginIndex 。 Unpaired surrogates within the text range are counted as one code point each.
        Parameter
        beginIndexThe first index of the text rangecharthe index of.
        endIndexThe last index of the text rangecharThe index after.
        Result
        the number of Unicode code points in the specified text range
        Exception
        IndexOutOfBoundsException- ifbeginIndexis negative, orendIndexgreater than thisStringthe length of, orbeginIndexgreater thanendIndex 。
        Starting from the following version:
        1.5
      • offsetByCodePoints

        public int offsetByCodePoints​(int index,
                                      int codePointOffset)
        Return thisStringthe index in, which starts from the givenindexOffsetcodePointOffsetcode point. byindexandcodePointOffsetUnpaired surrogates in the given text range count as one code point each.
        Parameter
        indexThe index to be offset
        codePointOffsetThe offset in code points
        Result
        the index atString
        Exception
        IndexOutOfBoundsException- ifindexis negative or greater than thisStringThe length, or ifcodePointOffsetis positive and fromindexThe substring starting at the specified index is shorter thancodePointOffsetcode points, or ifcodePointOffsetis negative andindexThe substring preceding the specified index is shorter than the absolute valuecodePointOffsetcode point.
        Starting from the following version:
        1.5
      • getChars

        public void getChars​(int srcBegin,
                             int srcEnd,
                             char[] dst,
                             int dstBegin)
        Copies characters from this string into the destination character array.

        The first character to be copied is the indexsrcBegin ; The last character to be copied is located at indexsrcEnd-1(therefore the total number of characters to be copied issrcEnd-srcBegin )。 characters are copied todstOf subdstfrom indexdstBeginStarts at and ends at the index:

             dstBegin + (srcEnd-srcBegin) - 1
         
        Parameter
        srcBeginThe index of the first character in the string to copy.
        srcEndThe index after the last character in the string to copy.
        dst- target array.
        dstBeginThe starting offset in the destination array.
        Exception
        IndexOutOfBoundsException- if any of the following conditions is satisfied:
        • srcBeginis negative.
        • srcBegingreater thansrcEnd
        • srcEndgreater than the length of this string
        • dstBeginis negative
        • dstBegin+(srcEnd-srcBegin)greater thandst.length
      • getBytes

        @Deprecated(since="1.1")
        public void getBytes​(int srcBegin,
                             int srcEnd,
                             byte[] dst,
                             int dstBegin)
        Deprecated.
        This method does not properly convert characters into bytes. As of JDK 1.1, the preferred way to do this is via the getBytes() method, which uses the platform's default charset.
        Copies characters from this string into the destination byte array. Each byte receives the 8 low-order bits of the corresponding character. The eight high-order bits of each character are not copied and do not participate in the transfer in any way.

        The first character to be copied is the indexsrcBegin ; The last character to be copied is located at indexsrcEnd-1 。 the total number of characters to be copied issrcEnd-srcBegin 。 The characters converted to bytes are copied todstOf subdstfrom indexdstBeginStarts at and ends at the index:

             dstBegin + (srcEnd-srcBegin) - 1
         
        Parameter
        srcBeginThe index of the first character in the string to copy.
        srcEndThe index after the last character in the string to copy.
        dst- target array
        dstBeginThe starting offset in the destination array.
        Exception
        IndexOutOfBoundsException- if any of the following conditions is satisfied:
        • srcBeginis negative
        • srcBegingreater thansrcEnd
        • srcEndgreater than the length of this String
        • dstBeginis negative
        • dstBegin+(srcEnd-srcBegin)greater thandst.length
      • getBytes

        public byte[] getBytes​(String charsetName)
                        throws UnsupportedEncodingException
        Using the specified charset, thisStringEncodes the string into a sequence of bytes, storing the result into a new byte array.

        The behavior of this method is unspecified when this string cannot be encoded in the given charset. When more control over the encoding process is required, useCharsetEncoderclass.

        Parameter
        charsetName- supportedcharsetname of
        Result
        the resulting byte array
        Exception
        UnsupportedEncodingException- if the specified charset is not supported
        Starting from the following version:
        1.1
      • getBytes

        public byte[] getBytes​(Charset charset)
        Uses the givencharsetPut thisStringEncodes the string into a sequence of bytes, storing the result into a new byte array.

        This method always uses this charset's default replacement byte array to replace malformed input and unmappable character sequences. When more control over the encoding process is required, useCharsetEncoderclass.

        Parameter
        charset-TheCharsetis used to encodeString
        Result
        the resulting byte array
        Starting from the following version:
        1.6
      • getBytes

        public byte[] getBytes()
        Using the platform's default charset, thisStringEncodes the string into a sequence of bytes, storing the result into a new byte array.

        The behavior of this method is unspecified when this string cannot be encoded in the default charset. When more control over the encoding process is required, useCharsetEncoderclass.

        Result
        the resulting byte array
        Starting from the following version:
        1.1
      • equals

        public boolean equals​(Object anObject)
        Compares this string to the specified object. if and only if the argument is notnullAnd isStringWhen the object represents the same character sequence as this object, the result istrue 。

        For finer-grained string comparison, seeCollator 。

        Override:
        equalsIn classObject
        Parameter
        anObject- comparisonStringobject of
        Result
        trueIf the given object representsStringa string equivalent to this string,falseOtherwise
        See also:
        compareTo(String) , equalsIgnoreCase(String)
      • contentEquals

        public boolean contentEquals​(StringBuffer sb)
        this string with the specifiedStringBuffer 。 the result istrue, if, if this is onlyStringRepresents the same sequence of characters as specifiedStringBuffer 。 this method inStringBuffersynchronized on

        For finer-grained string comparison, seeCollator 。

        Parameter
        sb- useStringBufferto compare thisString
        Result
        trueif thisStringrepresents the same character sequence as the specifiedStringBufferthe same character sequence, otherwisefalse
        Starting from the following version:
        1.4
      • contentEquals

        public boolean contentEquals​(CharSequence cs)
        this string with the specifiedCharSequence 。 if and only if thisStringWhen it represents the same sequence of char values as the specified sequence, the result istrue 。 Note that ifCharSequenceYesStringBufferthen the method will synchronize on it.

        For fine-grained string comparison, seeCollator 。

        Parameter
        cs- compare thisStringsequence of
        Result
        trueif thisStringrepresents the same sequence of char values as the specified sequence, otherwisefalse
        Starting from the following version:
        1.5
      • equalsIgnoreCase

        public boolean equalsIgnoreCase​(String anotherString)
        Put thisStringwith anotherStringCompares, ignoring case. Two strings are considered equal ignoring case if they have the same length and corresponding characters in the two strings are equal ignoring case.

        If at least one of the following conditions is satisfied, the two charactersc1andc2are considered the same ignoring case:

        • two characters are the same (by==operator comparison)
        • calling on each characterCharacter.toLowerCase(Character.toUpperCase(char))will produce the same result

        Note that this methodNoLocale considerations, and may lead to unsatisfactory results for a particular locale. CollatorThe class provides locale-sensitive comparison.

        Parameter
        anotherString- useStringto compare thisStringComparison
        Result
        trueif the argument is notnulland it represents an equivalentStringignoring case; otherwise isfalse
        See also:
        equals(Object)
      • compareTo

        public int compareTo​(String anotherString)
        Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the string. thisStringThe character sequence represented by this object is compared lexicographically with the character sequence represented by the parameter string. if thisStringIf the object is lexicographically ordered before the argument string, the result is a negative integer. if thisStringIf the object lexicographically follows the argument string, the result is a positive integer. If the strings are equal, the result is zero; compareToInequals(Object)method returns0returns exactlytrue 。

        This is the definition of lexicographic ordering. if twoStringDifferent,ThenThey are in某itemsIndex处HasNosamecharacters of,TheseStringYesTwoStringofvalidIndex, ortheyoflengthDifferent,ortwoallYes。 If they have different characters at one or more index positions, then letkis the smallest index; Then, by using<the operator determines its positionkThe string whose character at a given position has a smaller value precedes the other string lexicographically. In this case,compareToReturns the position in the two stringskthe two character values atk- i.e., the value:

         this.charAt(k)-anotherString.charAt(k)
         
        If they have no differing index positions, then the shorter string lexicographically precedes the longer string. In this case,compareToReturns the difference in string length - that is, the value:
         this.length()-anotherString.length()
         

        For finer-grained string comparison, seeCollator 。

        Specified by:
        compareToInComparable<String>
        Parameter
        anotherString- to be comparedString 。
        Result
        If the argument string equals this string, the value0 ; If this string is lexicographically less than the string argument, then less than0 ; If this string is lexicographically greater than the string argument, the value is greater than0 。
      • compareToIgnoreCase

        public int compareToIgnoreCase​(String str)
        Compares two strings lexicographically, ignoring case differences. This method returns an integer whose sign is the callcompareToan integer, where the normalized version of the string is obtained by calling ... on each characterCharacter.toLowerCase(Character.toUpperCase(character))eliminates case differences.

        Note that this methodNoLocale consideration, and will result in unsatisfactory ordering for certain language environments. CollatorThe class provides locale-sensitive comparison.

        Parameter
        str- to be comparedString 。
        Result
        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.
        Starting from the following version:
        1.2
        See also:
        Collator
      • regionMatches

        public boolean regionMatches​(int toffset,
                                     String other,
                                     int ooffset,
                                     int len)
        Tests whether two string regions are equal.

        Put thisStringThe substring of this object is compared with the substring of the argument other. If these substrings represent the same character sequence, then the result is true. this to be comparedStringthe substring of the object from indextoffsetstart, lengthlen 。 The other substring to be compared begins at indexooffsetstart, lengthlen 。 The result is true if and only if at least one of the following conditions is satisfied:false :

        • toffsetis negative.
        • ooffsetis negative.
        • toffset+lengreater than thisStringThe length of the object.
        • ooffset+lenis greater than the length of the other argument.
        • there are some non-negative integerskless thanlen, such that:this.charAt(toffset + k ) != other.charAt(ooffset + k )

        Note that this methodNothe location is considered. CollatorThe class provides locale-sensitive comparison.

        Parameter
        toffset- this stringtoffsetThe starting offset of the region.
        otherThe string argument.
        ooffset- string argumentooffsetThe starting offset of the region.
        lenThe number of characters to compare.
        Result
        trueIf the specified subregion of this string exactly matches the specified subregion of the string argument; otherwise isfalse 。
      • regionMatches

        public boolean regionMatches​(boolean ignoreCase,
                                     int toffset,
                                     String other,
                                     int ooffset,
                                     int len)
        Tests whether two string regions are equal.

        Put thisStringthe substring of the object with the argumentotherperform on the substring ofother 。 If these substrings represent the same character sequence, the result istrue, if and only ifignoreCaseWhen true, case is ignored. this to be comparedStringthe substring of the object from indextoffsetstart, lengthlen 。 the substring to be comparedotherfrom indexooffsetstart, lengthlen 。 result isfalseIf and only if at least one of the following conditions is met:

        • toffsetis negative.
        • ooffsetis negative.
        • toffset+lengreater than thisStringThe length of the object.
        • ooffset+lenis greater than the length of the other argument.
        • ignoreCaseYesfalseand there are some non-negative integerskless thanlenlike this:
           this.charAt(toffset+k) != other.charAt(ooffset+k)
           
        • ignoreCaseYestrueand there are some non-negative integerskless thanlenlike this:
           Character.toLowerCase(Character.toUpperCase(this.charAt(toffset+k))) !=
               Character.toLowerCase(Character.toUpperCase(other.charAt(ooffset+k)))
           

        Note that this methodNowhen locale considerations would lead to undesirable results for a particular localeignoreCaseistrue 。 CollatorThe class provides locale-sensitive comparison.

        Parameter
        ignoreCase- if it istrueignore case when comparing characters.
        toffset- this stringtoffsetThe starting offset of the region.
        otherThe string argument.
        ooffset- string argumentooffsetThe starting offset of the region.
        lenThe number of characters to compare.
        Result
        trueIf the specified subregion of this string matches the specified subregion of the string argument; otherwise isfalse 。 Whether the match is an exact match or is case-insensitive depends onignoreCaseparameters.
      • startsWith

        public boolean startsWith​(String prefix,
                                  int toffset)
        Tests whether the substring of this string beginning at the specified index starts with the specified prefix.
        Parameter
        prefix- prefix.
        toffsetThe index from which to start searching this string.
        Result
        trueIf the character sequence represented by the argument is from indextoffsetthe prefix of the substring of this object that begins; otherwise isfalse 。 iftoffsetis negative or greater than thisStringthe length of the object, then the result isfalse ; Otherwise, the result is the same as the result of the expression
          this.substring(toffset).startsWith(prefix) 
      • startsWith

        public boolean startsWith​(String prefix)
        Tests whether this string starts with the specified prefix.
        Parameter
        prefix- prefix.
        Result
        trueIf the character sequence represented by the argument is a prefix of the character sequence represented by this string; otherwise isfalse 。 It should also be noted thattrueIf the argument is an empty string or equal to this, it will be returnedStringas determined by the objectequals(Object)method.
        Starting from the following version:
        1.0
      • endsWith

        public boolean endsWith​(String suffix)
        Tests whether this string ends with the specified suffix.
        Parameter
        suffix- suffix.
        Result
        trueIf the character sequence represented by the argument is a suffix of the character sequence represented by this object; otherwise isfalse 。 Note that the result will betrueIf the argument is an empty string or equals thisStringas determined by the objectequals(Object)method.
      • hashCode

        public int hashCode()
        Returns the hash code for this string. Stringthe object's hash code is computed as
         s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
         
        Usageintarithmetic, wheres[i]is the index of the stringicharacters,nis the length of the string,^denotes exponentiation. (The hash code of an empty string is zero.)
        Override:
        hashCodeIn classObject
        Result
        The hash code value of this object.
        See also:
        Object.equals(java.lang.Object) , System.identityHashCode(java.lang.Object)
      • indexOf

        public int indexOf​(int ch)
        Returns the index within this string of the first occurrence of the specified character. if in thisStringThe value appearing in the character sequence represented by the object ischthe character, returns the index of the first such occurrence (in Unicode code units). For values in the range 0 to 0xFFFF, inclusive.ch, this is the minimum valuek, such that:
         this.charAt(k) == ch
         
        is true. forchfor other values, it is the minimum valuek, such that:
         this.codePointAt(k) == ch
         
        is true. In either case, if no such character occurs in this string, then -1 is returned.-1 。
        Parameter
        ch- Character (Unicode code point).
        Result
        the index of the first occurrence of the character in the character sequence represented by this object, if the character does not occur,-1 。
      • indexOf

        public int indexOf​(int ch,
                           int fromIndex)
        Returns the index in this string of the first occurrence of the specified character, searching from the specified index.

        if the index is not less thanfromIndex, thisStringThe value appearing in the character sequence represented by the object ischof the character, then returns the index of the first such occurrence. For values within the range 0 to 0xFFFF (inclusive)chvalue, which is the minimumk, such that:

         (this.charAt(k) == ch) && (k >= fromIndex)
         
        is true. forchfor other values, it is the minimum valuek, such that:
         (this.codePointAt(k) == ch) && (k >= fromIndex)
         
        is true. In either case, if at the positionfromIndexIf no such character appears in this string at or after this position, then return-1 。

        fromIndexthere is no limit on the value. If it is negative, it has the same effect as zero: the entire string may be searched. If it is greater than the length of this string, it has the same effect as being equal to the length of this string: returns-1 。

        All indices are based oncharSpecified by the value (Unicode code unit).

        Parameter
        ch- Character (Unicode code point).
        fromIndex- the index from which to start the search.
        Result
        the index of the first occurrence of the character in the character sequence represented by this object, greater than or equal tofromIndexif the character does not occur,-1 。
      • lastIndexOf

        public int lastIndexOf​(int ch)
        Returns the index within this string of the last occurrence of the specified character. For the range 0 to 0xFFFF (inclusive)chvalue,chthe index (in Unicode code units) is the maximumk,like this:
         this.charAt(k) == ch
         
        is true. forchfor other values, it is the maximum valuek, such that:
         this.codePointAt(k) == ch
         
        is true. In either case, if no such character occurs in this string, then -1 is returned.-1 。 Searches backward starting from the last characterString 。
        Parameter
        ch- Character (Unicode code point).
        Result
        the index of the last occurrence of the character in the character sequence represented by this object, if the character does not occur,-1 。
      • lastIndexOf

        public int lastIndexOf​(int ch,
                               int fromIndex)
        Returns the index within the string of the last occurrence of the specified character, searching backward from the specified index. For the range 0 to 0xFFFF (inclusive)chvalue, the returned index is the maximumk, such that:
         (this.charAt(k) == ch) && (k <= fromIndex)
         
        is true. forchfor other values, it is the maximum valuek, such that:
         (this.codePointAt(k) == ch) && (k <= fromIndex)
         
        is true. In either case, if at the positionfromIndexIf no such character occurs in this string at or before the position, then return-1 。

        All indices are based oncharSpecified by the value (Unicode code unit).

        Parameter
        ch- a character (Unicode code point).
        fromIndex- the index from which to start searching. fromIndexthere is no limit on the value. If it is greater than or equal to the length of the string, it has the same effect as if it were equal to one less than the length of the string: the entire string can be searched. If it is negative, it has the same effect as -1: returns -1.
        Result
        the index of the last occurrence of the character in the character sequence represented by this object that is less than or equal tofromIndex, if the character does not occur before that point,-1 。
      • indexOf

        public int indexOf​(String str)
        Returns the index within the string of the first occurrence of the specified substring.

        The returned index is the minimum valuek, where:

           this.startsWith(str, k)  
        if there is no such valuekexists, then-1returns.
        Parameter
        str- the substring to search for.
        Result
        the index of the first occurrence of the specified substring, if there is no such occurrence,-1 。
      • indexOf

        public int indexOf​(String str,
                           int fromIndex)
        Returns the index within the string of the first occurrence of the specified substring, starting at the specified index.

        The returned index is the minimum valuek, where:

           k >= Math.min(fromIndex, this.length()) && this.startsWith(str, k)  
        if there is no such valuekexists, then-1returns.
        Parameter
        str- the substring to search for.
        fromIndex- the index from which to start the search.
        Result
        the index of the first occurrence of the specified substring, starting at the specified index, if there is no such occurrence-1 。
      • lastIndexOf

        public int lastIndexOf​(String str)
        Returns the index within the string of the last occurrence of the specified substring. The last occurrence of the empty string "" is considered to occur at the index valuethis.length() 。

        The returned index is the maximum valuek, where:

           this.startsWith(str, k)  
        if there is no such valuekexists, then-1returns.
        Parameter
        str- the substring to search for.
        Result
        the index of the last occurrence of the specified substring, if there is no such occurrence,-1 。
      • lastIndexOf

        public int lastIndexOf​(String str,
                               int fromIndex)
        Returns the index within the string of the last occurrence of the specified substring, searching backward from the specified index.

        The returned index is the maximum valuek, where:

           k <= Math.min(fromIndex, this.length()) && this.startsWith(str, k)  
        if there is no such valuekexists, then-1returns.
        Parameter
        str- the substring to search for.
        fromIndex- the index from which to start the search.
        Result
        The index of the last occurrence of the specified substring, searching backward from the specified index, or -1 if there is no such occurrence.-1 。
      • substring

        public String substring​(int beginIndex)
        Returns a string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.

        Example:

         "unhappy".substring(2) returns "happy"
         "Harbison".substring(3) returns "bison"
         "emptiness".substring(9) returns "" (an empty string)
         
        Parameter
        beginIndexThe starting index, inclusive.
        Result
        The specified substring.
        Exception
        IndexOutOfBoundsException- ifbeginIndexis negative or greater than thisStringthe length of the object.
      • substring

        public String substring​(int beginIndex,
                                int endIndex)
        Returns a string that is a substring of this string. Substring from the specifiedbeginIndexstarts, and extends to the indexendIndex - 1character at. Therefore the length of the substring isendIndex-beginIndex 。

        Example:

         "hamburger".substring(4, 8) returns "urge"
         "smiles".substring(1, 5) returns "mile"
         
        Parameter
        beginIndexThe starting index, inclusive.
        endIndexThe end index, exclusive.
        Result
        The specified substring.
        Exception
        IndexOutOfBoundsException- ifbeginIndexis negative, orendIndexgreater than thisStringThe length of the object, orbeginIndexgreater thanendIndex 。
      • subSequence

        public CharSequence subSequence​(int beginIndex,
                                        int endIndex)
        Returns a character sequence that is a subsequence of this sequence.

        The form of calling this method

         str.subSequence(begin, end)
        The behavior is exactly the same as calling
         str.substring(begin, end)
        Specified by:
        subSequenceIn the interfaceCharSequence
        API Note:
        Define this method so thatStringA class can implementCharSequenceInterface.
        Parameter
        beginIndexThe starting index, inclusive.
        endIndexThe end index, exclusive.
        Result
        the specified subsequence.
        Exception
        IndexOutOfBoundsException- ifbeginIndexorendIndexis negative, ifendIndexgreater thanlength(), orbeginIndexgreater thanendIndex
        Starting from the following version:
        1.4
      • concat

        public String concat​(String str)
        Concatenates the specified string to the end of this string.

        If the length of the argument string is0, then returns thisStringObject. otherwise, returns aStringobject that represents a character sequence, the character sequence being from thisStringThe concatenation of the character sequence represented by this object and the character sequence represented by the argument string.

        Example:

         "cares".concat("s") returns "caress"
         "to".concat("get").concat("her") returns "together"
         
        Parameter
        str-TheStringconcatenated to the end of this stringString 。
        Result
        a string that represents the concatenation of this object's string followed by the string argument's characters.
      • replace

        public String replace​(char oldChar,
                              char newChar)
        Returns a string resulting from replacing all occurrencesoldCharin this stringnewChar 。

        if the characteroldChardoes not occur in the character sequence represented by thisStringobject, then the referenceStringThe object is returned. otherwise,StringThe returned object represents a character sequence identical to the character sequence represented by this object.Stringexcept for each occurrence of the object,oldCharby replacing occurrencesnewChar 。

        Example:

         "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)
         
        Parameter
        oldChar- old char.
        newChar- new char.
        Result
        byoldChareach match replaced witholdChar , newCharA string derived from this string.
      • matches

        public boolean matches​(String regex)
        Determines whether this string is equal to the givenregular expressionmatch.

        Callstr .matches( regex )This form of the method produces the same result asExpressionexactly the same result

        Pattern. matches(regex, str)
        Parameter
        regex- the regular expression to which this string is to be matched
        Result
        trueif and only if this string matches the given regular expression
        Exception
        PatternSyntaxExceptionIf the syntax of the regular expression is invalid
        Starting from the following version:
        1.4
        See also:
        Pattern
      • contains

        public boolean contains​(CharSequence s)
        Returns true if and only if this string contains the specified sequence of char values.
        Parameter
        s- the sequence to search for
        Result
        If this string containssreturns true, otherwises false
        Starting from the following version:
        1.5
      • replaceFirst

        public String replaceFirst​(String regex,
                                   String replacement)
        Replace the given ... with the given ...regular expressionReplaces the first substring of this string that matches.

        Callstr .replaceFirst(form of this methodregex , repl )Produces exactly the same result as the expression

        Pattern.compile(regex).matcher(str).replaceFirst(repl)

        Please note that the backslash in the replacement string (\) and the dollar sign ($) may cause the result to differ from the result when it is treated as a literal replacement string; seeMatcher.replaceFirst(java.lang.String) 。 If necessary, useMatcher.quoteReplacement(java.lang.String)to suppress the special meaning of these characters.

        Parameter
        regex- the regular expression to which this string is to be matched
        replacement- the string to be substituted for the first match
        Result
        resulting from thisString
        Exception
        PatternSyntaxExceptionIf the syntax of the regular expression is invalid
        Starting from the following version:
        1.4
        See also:
        Pattern
      • replaceAll

        public String replaceAll​(String regex,
                                 String replacement)
        Replace the given ... with the given ...regular expressionReplaces each substring of this string that matches.

        Callstr .replaceAll(form of this methodregex , repl )Produces exactly the same result as the expression

        Pattern.compile(regex).matcher(str).replaceAll(repl)

        Please note that the backslash in the replacement string (\) and the dollar sign ($) may cause the result to differ from the result of treating it as a literal replacement string; seeMatcher.replaceAll 。 If necessary, useMatcher.quoteReplacement(java.lang.String)to suppress the special meaning of these characters.

        Parameter
        regex- the regular expression to which this string is to be matched
        replacementThe string to replace each match with
        Result
        resulting from thisString
        Exception
        PatternSyntaxExceptionIf the syntax of the regular expression is invalid
        Starting from the following version:
        1.4
        See also:
        Pattern
      • replace

        public String replace​(CharSequence target,
                              CharSequence replacement)
        Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. Replacement from the beginning to the end of the string, for example, in the string "aaa", replacing "aa" with "b" will result in "ba" rather than "ab".
        Parameter
        targetThe sequence of char values to be replaced
        replacementThe replacement sequence of char values
        Result
        result string
        Starting from the following version:
        1.5
      • split

        public String[] split​(String regex,
                              int limit)
        Splits this string around the givenof a regular expressionmatchitem 。

        The array returned by this method contains each substring of this string that is terminated by another substring matching the given expression, or by the end of the string. The substrings in the array are arranged in the order in which they appear in this string. If the expression does not match any part of the input, then the resulting array has just one element, namely that string.

        When there is a positive-width match at the beginning of the string, an empty leading substring is included at the beginning of the resulting array. However, a zero-width match at the beginning never produces such an empty leading substring.

        limitThe parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array.

        • ifLimitis positive, the pattern will be applied at mostLimit- 1 times, the length of the array will not exceedLimit, and the last entry of the array will contain all input beyond the last matched delimiter.

        • ifLimitIf it is zero, the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

        • ifLimitIf negative, then the pattern will be applied as many times as possible, and the array can have any length.

        For example, the string"boo:and:foo"Using the following parameters produces the following results:

        Split example showing regex, limit, and result
        Regex Limit Result
        : 2 { "boo", "and:foo" }
        5 { "boo", "and", "foo" }
        -2 { "boo", "and", "foo" }
        o 5 { "b", "", ":and:f", "", "" }
        -2 { "b", "", ":and:f", "", "" }
        0 { "b", "", ":and:f" }

        Callstrthis method of the form。 split( regex , n )produces the same result as the expression

        Pattern.compile(regex).split(str, n)
        Parameter
        regexThe delimiting regular expression
        limit- result threshold, as described above
        Result
        an array of strings computed by splitting this string around matches of the given regular expression
        Exception
        PatternSyntaxExceptionIf the syntax of the regular expression is invalid
        Starting from the following version:
        1.4
        See also:
        Pattern
      • split

        public String[] split​(String regex)
        Splits this string around the givenof a regular expressionmatchitem 。

        This method behaves as if by calling the two-argument method with the given expression and a limit parameter of zero.splitsame as the method. Therefore, trailing empty strings are not included in the result array.

        For example, the string"boo:and:foo"Using the following expression produces the following result:

        Split examples showing regex and result
        Regex Result
        : { "boo", "and", "foo" }
        o { "b", "", ":and:f" }
        Parameter
        regexThe delimiting regular expression
        Result
        an array of strings computed by splitting this string around matches of the given regular expression
        Exception
        PatternSyntaxExceptionIf the syntax of the regular expression is invalid
        Starting from the following version:
        1.4
        See also:
        Pattern
      • join

        public static String join​(CharSequence delimiter,
                                  CharSequence... elements)
        returned byCharSequence elementsa new String composed of a copy that is identical to the specifieddelimiterthe copies are joined together.
        For example,
        
             String message = String.join("-", "Java", "is", "cool");
             // message returned is: "Java-is-cool"
         
        Note that if the element is null, then adding"null" 。
        Parameter
        delimiterThe delimiter used to separate each element
        elementsThe elements to be joined together.
        Result
        a newString, which consists of the specifiedelementsseparated bydelimiter
        Exception
        NullPointerException- ifdelimiterorelementsYesnull
        Starting from the following version:
        1.8
        See also:
        StringJoiner
      • join

        public static String join​(CharSequence delimiter,
                                  Iterable<? extends CharSequence> elements)
        returned byStringthe new one composed of copies ofString, whereCharSequence elementsspecifieddelimitera copy of.
        For example,
        
             List<String> strings = List.of("Java", "is", "cool");
             String message = String.join(" ", strings);
             //message returned is: "Java is cool"
        
             Set<String> strings =
                 new LinkedHashSet<>(List.of("Java", "is", "very", "cool"));
             String message = String.join("-", strings);
             //message returned is: "Java-is-very-cool"
         
        Note that if a single element isnull, then add"null" 。
        Parameter
        delimiter- the character sequence used to separate each of the elementselementsin the resultingString
        elements - IterableMake itelementsjoined together.
        Result
        byelementsa new String composed of the parametersString
        Exception
        NullPointerException- ifdelimiterorelementsYesnull
        Starting from the following version:
        1.8
        See also:
        join(CharSequence,CharSequence...) , StringJoiner
      • toLowerCase

        public String toLowerCase​(Locale locale)
        using the givenLocalerules of thisStringall characters converted toLocale 。 case mapping based onCharacterThe version of the Unicode standard specified by the class. Since case mapping is not always a 1:1 character mapping, the resultingStringmay be different from the originalStringthe length differs.

        Examples of lowercase mapping are shown in the following table:

        Lowercase mapping examples showing language code of locale, upper case, lower case, and description Language Code of Locale Upper Case Lower Case Description tr (Turkish) \u0130 \u0069 capital letter I with dot above -> small letter i tr (Turkish) \u0049 \u0131 capital letter I -> small letter dotless i (all) French Fries french fries lowercased all chars in String (all) ΙΧΘΥΣ ιχθυσ lowercased all chars in String
        Parameter
        locale- use the case conversion rules of this locale
        Result
        String, converted to lowercase.
        Starting from the following version:
        1.1
        See also:
        toLowerCase() , toUpperCase() , toUpperCase(Locale)
      • toLowerCase

        public String toLowerCase()
        Using the rules of the default locale, thisStringAll characters are converted to lowercase. This is equivalent to callingtoLowerCase(Locale.getDefault()) 。

        Note:This method is locale-sensitive, and if used with strings intended to be interpreted independently of the locale, it may produce unexpected results. Examples are programming language identifiers, protocol keys, and HTML tags. For example,"TITLE".toLowerCase()In the Turkish locale, returns"t\u0131tle", where 'ı' is the Latin small letter dotless i character. To obtain correct results for locale-insensitive strings, usetoLowerCase(Locale.ROOT) 。

        Result
        String, converted to lowercase.
        See also:
        toLowerCase(Locale)
      • toUpperCase

        public String toUpperCase​(Locale locale)
        using the givenLocalerules of thisStringAll characters are converted to uppercase. case mapping based onCharacterThe version of the Unicode standard specified by the class. Because case mapping is not always a 1:1 char mapping, the resultingStringmay be different from the originalStringthe length differs.

        Examples of locale-sensitive and 1:M case mappings are shown in the table below.

        Examples of locale-sensitive and 1:M case mappings. Shows Language code of locale, lower case, upper case, and description. Language Code of Locale Lower Case Upper Case Description tr (Turkish) \u0069 \u0130 small letter i -> capital letter I with dot above tr (Turkish) \u0131 \u0049 small letter dotless i -> capital letter I (all) \u00df \u0053 \u0053 small letter sharp s -> two letters: SS (all) Fahrvergnügen FAHRVERGNÜGEN
        Parameter
        locale- use the case conversion rules of this locale
        Result
        String, converted to uppercase.
        Starting from the following version:
        1.1
        See also:
        toUpperCase() , toLowerCase() , toLowerCase(Locale)
      • toUpperCase

        public String toUpperCase()
        Using the rules of the default locale, thisStringAll characters are converted to uppercase. This method is equivalent totoUpperCase(Locale.getDefault()) 。

        Note:This method is locale-sensitive, and if used with strings intended to be interpreted independently of the locale, it may produce unexpected results. Examples are programming language identifiers, protocol keys, and HTML tags. For example,"title".toUpperCase()In the Turkish locale, returns"T\u0130TLE", where '\u0130' is the Latin capital letter I with dot above. To obtain correct results for locale-insensitive strings, usetoUpperCase(Locale.ROOT) 。

        Result
        String, converted to uppercase.
        See also:
        toUpperCase(Locale)
      • trim

        public String trim()
        Return a string whose value is this string, with all leading and trailing spaces removed, where space is defined as having code point less than or equal to'U+0020'any character (space character).

        if thisStringThe object represents an empty character sequence, or the first and last characters of the character sequence represented by this object.StringObjects all have non-space codes (as defined above), and then the baseStringThe object is returned.

        Otherwise, if all characters in this string are whitespace (as described above), then returns a string representing the empty stringStringObject.

        otherwise, letkis the index of the first character in the string whose code is not whitespace (as defined above), and letmis the index of the last character in the string whose code is not a space (as defined above). returns aStringobject representing a substring of this string, which begins at indexkstarts with the character at the indexmends at the character at, i.e.this.substring(k, m + 1)the result of.

        This method can be used to trim space from the beginning and end of a string (as described above).

        Result
        a string whose value is this string, with all leading and trailing space removed, or this string if there are no leading or trailing spaces.
      • strip

        public String strip()
        Returns a string whose value is this string, with all leading and trailing whitespace removed.white space 。

        if thisStringThe object represents an empty string, or all code points in this string arewhite space, then an empty string is returned.

        Otherwise, returns a substring of this string that begins with the first character that is notwhite spaceofstarting with a code point, including the last one that is notwhite spaceofcode point.

        This method can be used to strip from the beginning and end of a stringwhite space 。

        Result
        a string whose value is this string, with all leading and trailing white space removed
        Starting from the following version:
        11
        See also:
        Character.isWhitespace(int)
      • stripLeading

        public String stripLeading()
        Returns a string whose value is this string, with all leading whitespace removed.white space 。

        if thisStringThe object represents an empty string, or all code points in this string arewhite space, then an empty string is returned.

        Otherwise, returns a substring of this string that begins with the first character that is notwhite spaceofIt starts with a code point and includes the last code point of the string.

        This method can be used to trim from the beginning of the stringwhite space 。

        Result
        a string whose value is this string, with all leading white space removed
        Starting from the following version:
        11
        See also:
        Character.isWhitespace(int)
      • stripTrailing

        public String stripTrailing()
        Returns a string whose value is this string, with all trailing whitespace removed.white space 。

        if thisStringThe object represents an empty string, or all characters in this string arewhite space, then an empty string is returned.

        Otherwise, returns a substring of this string, beginning with the first code point of this string, and including the last one that is notwhite spaceofcode point.

        This method can be used to trim from the end of the stringwhite space 。

        Result
        a string whose value is this string, with all trailing white space removed
        Starting from the following version:
        11
        See also:
        Character.isWhitespace(int)
      • isBlank

        public boolean isBlank()
        If the string is empty or contains onlywhite spaceitemscode point, then returnstrue, otherwisefalse 。
        Result
        trueIf the string is empty or contains onlywhite spacecode point, otherwisefalse
        Starting from the following version:
        11
        See also:
        Character.isWhitespace(int)
      • lines

        public Stream<String> lines()
        Returns a stream of lines extracted from this string, separated by line terminators.

        line terminatoris one of the following: a line feed"\n"(U + 000A), carriage return character"\r"(U+000D), or a carriage return line feed immediately followed by"\r\n" (U + 000D U + 000A) 。

        One lineis a sequence of zero or more characters followed by a line terminator, or a sequence of one or more characters followed by the end of the string. A line does not include a line terminator.

        The stream returned by this method contains the lines appearing in this string.

        API Note:
        ThisOf the lineThe definition implies that an empty string has zero lines, and that there is no empty line after a line terminator at the end of the string.
        Implementation Note:
        By lazily providing elements and searching for new line terminators more quickly, this method provides better performance than split("\R").
        Result
        A stream of lines extracted from this string
        Starting from the following version:
        11
      • toString

        public String toString()
        This object (which is already a string!) is itself returned.
        Specified by:
        toStringIn the interfaceCharSequence
        Override:
        toStringIn classObject
        Result
        the string itself.
      • chars

        public IntStream chars()
        returninta stream of the elements in this sequencecharThe value is zero-extended. toof the surrogate code pointAny character is uninterpreted.
        Specified by:
        charsIn the interfaceCharSequence
        Result
        an IntStream of char values from this sequence
        Starting from the following version:
        9
      • codePoints

        public IntStream codePoints()
        Returns a stream of code point values from this sequence. Any surrogate pairs encountered in the sequence are combined, just likesame as Character.toCodePoint, the result is passed to the stream. Any other code unit (including ordinary BMP characters, unpaired surrogates, and undefined code units) will be zero-extended tointthe value, then passed to the stream.
        Specified by:
        codePointsIn the interfaceCharSequence
        Result
        An IntStream of Unicode code points pointing to this sequence.
        Starting from the following version:
        9
      • toCharArray

        public char[] toCharArray()
        Converts this string to a new character array.
        Result
        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.
      • format

        public static String format​(String format,
                                    Object... args)
        Returns a formatted string using the specified format string and arguments.

        The locale always used is determined byLocale.getDefault(Locale.Category)the returned locale, in which is specifiedFORMATcategory.

        Parameter
        format - A format string
        args- The argument referenced by a format specifier in the format string. If there are more arguments than format specifiers, the extra arguments are ignored. The number of parameters is variable and can be zero. the maximum number of parameters is limited byThe Java™ Virtual Machine SpecificationThe maximum dimension limit of Java arrays defined. nullthe behavior of the parameter depends onconversion 。
        Result
        the formatted string
        Exception
        IllegalFormatException- If the format string contains illegal syntax, a format specifier is incompatible with the given arguments, there are insufficient arguments for the given format string, or other illegal conditions. For a description of all possible format errors, see the formatter class specification'sDetailspart.
        Starting from the following version:
        1.5
        See also:
        Formatter
      • format

        public static String format​(Locale l,
                                    String format,
                                    Object... args)
        Returns a formatted string using the specified locale, format string, and arguments.
        Parameter
        l- applied when formattinglocale 。 iflYesnullthen localization is not applied.
        format - A format string
        args- The argument referenced by a format specifier in the format string. If there are more arguments than format specifiers, the extra arguments are ignored. The number of parameters is variable and can be zero. the maximum number of parameters is limited byThe Java™ Virtual Machine SpecificationThe maximum dimension limit of Java arrays defined. nullthe behavior on the argument depends onconversion 。
        Result
        the formatted string
        Exception
        IllegalFormatException- If the format string contains illegal syntax, a format specifier is incompatible with the given arguments, there are insufficient arguments for the given format string, or other illegal conditions. For a description of all possible format errors, see the formatter class specification'sDetailsPart
        Starting from the following version:
        1.5
        See also:
        Formatter
      • valueOf

        public static String valueOf​(Object obj)
        returnObjectThe string representation of the argument.
        Parameter
        obj - Object 。
        Result
        if the argument isnull, then the string equals"null" ; Otherwise, the return valueobj.toString() 。
        See also:
        Object.toString()
      • valueOf

        public static String valueOf​(char[] data)
        returncharthe string representation of the array argument. Copies the contents of the character array; Subsequent modification of the character array will not affect the returned string.
        Parameter
        data- character array.
        Result
        a Stringcontaining the characters of the character array.
      • valueOf

        public static String valueOf​(char[] data,
                                     int offset,
                                     int count)
        returncharThe string representation of a specific subarray of the array argument.

        offsetthe argument is a suboffsetthe index of the first character. countparameter specifies a subcountthe length of. The contents of the subarray are copied; Subsequent modification of the character array will not affect the returned string.

        Parameter
        data- character array.
        offsetThe initial offset of the subarray.
        countThe length of the subarray.
        Result
        a String, containing the characters of the specified subarray of the character array.
        Exception
        IndexOutOfBoundsException- ifoffsetis negative, orcountis negative, oroffset+countgreater thandata.length 。
      • copyValueOf

        public static String copyValueOf​(char[] data,
                                         int offset,
                                         int count)
        Equivalent tovalueOf(char[], int, int) 。
        Parameter
        data- character array.
        offsetThe initial offset of the subarray.
        countThe length of the subarray.
        Result
        a String, containing the characters of the specified subarray of the character array.
        Exception
        IndexOutOfBoundsException- ifoffsetis negative, orcountis negative, oroffset+countgreater thandata.length 。
      • copyValueOf

        public static String copyValueOf​(char[] data)
        Equivalent tovalueOf(char[]) 。
        Parameter
        data- character array.
        Result
        containing the characters of the character arrayString 。
      • valueOf

        public static String valueOf​(boolean b)
        returnbooleanThe string representation of the argument.
        Parameter
        b - a boolean 。
        Result
        if the argument istrue, then returns equal to"true"the string; otherwise, returns a value equal to"false"the string.
      • valueOf

        public static String valueOf​(char c)
        returncharThe string representation of the argument.
        Parameter
        c - a char 。
        Result
        a length of1the string,1contains the argumentcas its single character.
      • valueOf

        public static String valueOf​(int i)
        returnintThe string representation of the argument.

        the representation is exactly that of a one-argumentInteger.toStringthe representation returned by the method.

        Parameter
        i - int 。
        Result
        intThe string representation of the argument.
        See also:
        Integer.toString(int, int)
      • valueOf

        public static String valueOf​(long l)
        returnlongThe string representation of the argument.

        This representation is exactly that of an argumentLong.toStringthe representation returned by the method.

        Parameter
        l - a long 。
        Result
        longThe string representation of the argument.
        See also:
        Long.toString(long)
      • valueOf

        public static String valueOf​(float f)
        returnfloatThe string representation of the argument.

        This representation is exactly that of an argumentFloat.toStringthe representation returned by the method.

        Parameter
        f - a float 。
        Result
        floatThe string representation of the argument.
        See also:
        Float.toString(float)
      • valueOf

        public static String valueOf​(double d)
        returndoubleThe string representation of the argument.

        This representation is exactly that of an argumentDouble.toStringthe representation returned by the method.

        Parameter
        d - a double 。
        Result
        doubleThe string representation of the argument.
        See also:
        Double.toString(double)
      • intern

        public String intern()
        Returns the canonical representation of the string object.

        The initially empty string pool is maintained by the classStringprivately maintained.

        When the intern method is called, if the pool already contains a string equal toStringdetermined by the methodStringIf the string of the object is in the pool, then the string in the pool is returned. otherwise, thisStringobject is added to the pool, and a reference to thisStringreference to the object.

        Thus, for any two stringssandt , s.intern() == t.intern()Yestrueif and only ifs.equals(t)istrue 。

        All literal strings and string-valued constant expressions are interned. String literals inof The Java™ Language Specificationdefined in Section 3.10.5.

        Result
        a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings.
        See The Java™ Language Specification:
        3.10.5 String Literals
      • repeat

        public String repeat​(int count)
        Returns a string whose value is the concatenation of this string repeated.countTimes.

        If this string is empty or count is zero, then the empty string is returned.

        Parameter
        count- the number of repetitions
        Result
        A string consisting of this string repeatedcounttimes, or an empty string if this string is empty or count is zero.
        Exception
        IllegalArgumentException- ifcountis negative.
        Starting from the following version:
        11