欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

String类的研究

程序员文章站 2022-05-18 14:33:51
public final class string implements java.io.serializable, comparable, charsequence {...
public final class string
    implements java.io.serializable, comparable, charsequence
{
    /** the value is used for character storage. */
    private final char value[];

    /** the offset is the first index of the storage that is used. */
    private final int offset;

    /** the count is the number of characters in the string. */
    private final int count;
    /** cache the hash code for the string */
    private int hash; // default to 0

    /** use serialversionuid from jdk 1.0.2 for interoperability */
    private static final long serialversionuid = -6849794470754667710l;

    /**
     * class string is special cased within the serialization stream protocol.
     *
     * a string instance is written initially into an objectoutputstream in the
     * following format:
     *
     *      tc_string (utf string)
     * 
* the string is written by method dataoutput.writeutf. * a new handle is generated to refer to all future references to the * string instance within the stream. */ private static final objectstreamfield[] serialpersistentfields = new objectstreamfield[0]; /** * initializes a newly created {@code string} object so that it represents * an empty character sequence. note that use of this constructor is * unnecessary since strings are immutable. */ public string() { this.offset = 0; this.count = 0; this.value = new char[0]; } /** * initializes a newly created {@code string} object so that it represents * the same sequence of characters as the argument; in other words, the * newly created string is a copy of the argument string. unless an * explicit copy of {@code original} is needed, use of this constructor is * unnecessary since strings are immutable. * * @param original * a {@code string} */ public string(string original) { int size = original.count; char[] originalvalue = original.value; char[] v; if (originalvalue.length > size) { // the array representing the string is bigger than the new // string itself. perhaps this constructor is being called // in order to trim the baggage, so make a copy of the array. int off = original.offset; v = arrays.copyofrange(originalvalue, off, off+size); } else { // the array representing the string is the same // size as the string, so no point in making a copy. v = originalvalue; } this.offset = 0; this.count = size; this.value = v; } /** * allocates a new {@code string} so that it represents the sequence of * characters currently contained in the character array argument. the * contents of the character array are copied; subsequent modification of * the character array does not affect the newly created string. * * @param value * the initial value of the string */ public string(char value[]) { int size = value.length; this.offset = 0; this.count = size; this.value = arrays.copyof(value, size); } /** * allocates a new {@code string} that contains characters from a subarray * of the character array argument. the {@code offset} argument is the * index of the first character of the subarray and 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 newly created string. * * @param value * array that is the source of characters * * @param offset * the initial offset * * @param count * the length * * @throws indexoutofboundsexception * if the {@code offset} and {@code count} arguments index * characters outside the bounds of the {@code value} array */ public string(char value[], int offset, int count) { if (offset < 0) { throw new stringindexoutofboundsexception(offset); } if (count < 0) { throw new stringindexoutofboundsexception(count); } // note: offset or count might be near -1>>>1. if (offset > value.length - count) { throw new stringindexoutofboundsexception(offset + count); } this.offset = 0; this.count = count; this.value = arrays.copyofrange(value, offset, offset+count); } /** * allocates a new {@code string} that contains characters from a subarray * of the unicode code point array argument. the {@code offset} argument * is the index of the first code point of the subarray and the * {@code count} argument specifies the length of the subarray. the * contents of the subarray are converted to {@code char}s; subsequent * modification of the {@code int} array does not affect the newly created * string. * * @param codepoints * array that is the source of unicode code points * * @param offset * the initial offset * * @param count * the length * * @throws illegalargumentexception * if any invalid unicode code point is found in {@code * codepoints} * * @throws indexoutofboundsexception * if the {@code offset} and {@code count} arguments index * characters outside the bounds of the {@code codepoints} array * * @since 1.5 */ public string(int[] codepoints, int offset, int count) { if (offset < 0) { throw new stringindexoutofboundsexception(offset); } if (count < 0) { throw new stringindexoutofboundsexception(count); } // note: offset or count might be near -1>>>1. if (offset > codepoints.length - count) { throw new stringindexoutofboundsexception(offset + count); } int expansion = 0; int margin = 1; char[] v = new char[count + margin]; int x = offset; int j = 0; for (int i = 0; i < count; i++) { int c = codepoints[x++]; if (c < 0) { throw new illegalargumentexception(); } if (margin <= 0 && (j+1) >= v.length) { if (expansion == 0) { expansion = (((-margin + 1) * count) << 10) / i; expansion >>= 10; if (expansion <= 0) { expansion = 1; } } else { expansion *= 2; } int newlen = math.min(v.length+expansion, count*2); margin = (newlen - v.length) - (count - i); v = arrays.copyof(v, newlen); } if (c < character.min_supplementary_code_point) { v[j++] = (char) c; } else if (c <= character.max_code_point) { character.tosurrogates(c, v, j); j += 2; margin--; } else { throw new illegalargumentexception(); } } this.offset = 0; this.value = v; this.count = j; } /** * allocates a new {@code string} constructed from a subarray of an array * of 8-bit integer values. * *

the {@code offset} argument is the index of the first byte of the * subarray, and the {@code count} argument specifies the length of the * subarray. * *

each {@code byte} in the subarray is converted to a {@code char} as * specified in the method above. * * @deprecated this method does not properly convert bytes into characters. * as of jdk 1.1, the preferred way to do this is via the * {@code string} constructors that take a {@link * java.nio.charset.charset}, charset name, or that use the platform's * default charset. * * @param ascii * the bytes to be converted to characters * * @param hibyte * the top 8 bits of each 16-bit unicode code unit * * @param offset * the initial offset * @param count * the length * * @throws indexoutofboundsexception * if the {@code offset} or {@code count} argument is invalid * * @see #string(byte[], int) * @see #string(byte[], int, int, java.lang.string) * @see #string(byte[], int, int, java.nio.charset.charset) * @see #string(byte[], int, int) * @see #string(byte[], java.lang.string) * @see #string(byte[], java.nio.charset.charset) * @see #string(byte[]) */ @deprecated public string(byte ascii[], int hibyte, int offset, int count) { checkbounds(ascii, offset, count); char value[] = new char[count]; if (hibyte == 0) { for (int i = count ; i-- > 0 ;) { value[i] = (char) (ascii[i + offset] & 0xff); } } else { hibyte <<= 8; for (int i = count ; i-- > 0 ;) { value[i] = (char) (hibyte | (ascii[i + offset] & 0xff)); } } this.offset = 0; this.count = count; this.value = value; } /** * allocates a new {@code string} containing characters constructed from * an array of 8-bit integer values. each character cin the * resulting string is constructed from the corresponding component * b in the byte array such that: * *

     *     c == (char)(((hibyte & 0xff) << 8)
     *                         | (b & 0xff))
     * 
* * @deprecated this method does not properly convert bytes into * characters. as of jdk 1.1, the preferred way to do this is via the * {@code string} constructors that take a {@link * java.nio.charset.charset}, charset name, or that use the platform's * default charset. * * @param ascii * the bytes to be converted to characters * * @param hibyte * the top 8 bits of each 16-bit unicode code unit * * @see #string(byte[], int, int, java.lang.string) * @see #string(byte[], int, int, java.nio.charset.charset) * @see #string(byte[], int, int) * @see #string(byte[], java.lang.string) * @see #string(byte[], java.nio.charset.charset) * @see #string(byte[]) */ @deprecated public string(byte ascii[], int hibyte) { this(ascii, hibyte, 0, ascii.length); } /* common private utility method used to bounds check the byte array * and requested offset & length values used by the string(byte[],..) * constructors. */ private static void checkbounds(byte[] bytes, int offset, int length) { if (length < 0) throw new stringindexoutofboundsexception(length); if (offset < 0) throw new stringindexoutofboundsexception(offset); if (offset > bytes.length - length) throw new stringindexoutofboundsexception(offset + length); } /** * constructs a new {@code string} by decoding the specified subarray of * bytes using the specified charset. the length of the new {@code string} * is a function of the charset, and hence may not be equal to the length * of the subarray. * *

the behavior of this constructor when the given bytes are not valid * in the given charset is unspecified. the {@link * java.nio.charset.charsetdecoder} class should be used when more control * over the decoding process is required. * * @param bytes * the bytes to be decoded into characters * * @param offset * the index of the first byte to decode * * @param length * the number of bytes to decode * @param charsetname * the name of a supported {@linkplain java.nio.charset.charset * charset} * * @throws unsupportedencodingexception * if the named charset is not supported * * @throws indexoutofboundsexception * if the {@code offset} and {@code length} arguments index * characters outside the bounds of the {@code bytes} array * * @since jdk1.1 */ public string(byte bytes[], int offset, int length, string charsetname) throws unsupportedencodingexception { if (charsetname == null) throw new nullpointerexception("charsetname"); checkbounds(bytes, offset, length); char[] v = stringcoding.decode(charsetname, bytes, offset, length); this.offset = 0; this.count = v.length; this.value = v; } /** * constructs a new {@code string} by decoding the specified subarray of * bytes using the specified {@linkplain java.nio.charset.charset charset}. * the length of the new {@code string} is a function of the charset, and * hence may not be equal to the length of the subarray. * *

this method always replaces malformed-input and unmappable-character * sequences with this charset's default replacement string. the {@link * java.nio.charset.charsetdecoder} class should be used when more control * over the decoding process is required. * * @param bytes * the bytes to be decoded into characters * * @param offset * the index of the first byte to decode * * @param length * the number of bytes to decode * * @param charset * the {@linkplain java.nio.charset.charset charset} to be used to * decode the {@code bytes} * * @throws indexoutofboundsexception * if the {@code offset} and {@code length} arguments index * characters outside the bounds of the {@code bytes} array * * @since 1.6 */ public string(byte bytes[], int offset, int length, charset charset) { if (charset == null) throw new nullpointerexception("charset"); checkbounds(bytes, offset, length); char[] v = stringcoding.decode(charset, bytes, offset, length); this.offset = 0; this.count = v.length; this.value = v; } /** * constructs a new {@code string} by decoding the specified array of bytes * using the specified {@linkplain java.nio.charset.charset charset}. the * length of the new {@code string} is a function of the charset, and hence * 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 given charset is unspecified. the {@link * java.nio.charset.charsetdecoder} class should be used when more control * over the decoding process is required. * * @param bytes * the bytes to be decoded into characters * * @param charsetname * the name of a supported {@linkplain java.nio.charset.charset * charset} * * @throws unsupportedencodingexception * if the named charset is not supported * * @since jdk1.1 */ public string(byte bytes[], string charsetname) throws unsupportedencodingexception { this(bytes, 0, bytes.length, charsetname); } /** * constructs a new {@code string} by decoding the specified array of * bytes using the specified {@linkplain java.nio.charset.charset charset}. * the length of the new {@code string} is a function of the charset, and * hence may not be equal to the length of the byte array. * *

this method always replaces malformed-input and unmappable-character * sequences with this charset's default replacement string. the {@link * java.nio.charset.charsetdecoder} class should be used when more control * over the decoding process is required. * * @param bytes * the bytes to be decoded into characters * * @param charset * the {@linkplain java.nio.charset.charset charset} to be used to * decode the {@code bytes} * * @since 1.6 */ public string(byte bytes[], charset charset) { this(bytes, 0, bytes.length, charset); } /** * constructs a new {@code string} by decoding the specified subarray of * bytes using the platform's default charset. the length of the new * {@code string} is a function of the charset, and hence may not be equal * to the length of the subarray. * *

the behavior of this constructor when the given bytes are not valid * in the default charset is unspecified. the {@link * java.nio.charset.charsetdecoder} class should be used when more control * over the decoding process is required. * * @param bytes * the bytes to be decoded into characters * * @param offset * the index of the first byte to decode * * @param length * the number of bytes to decode * * @throws indexoutofboundsexception * if the {@code offset} and the {@code length} arguments index * characters outside the bounds of the {@code bytes} array * * @since jdk1.1 */ public string(byte bytes[], int offset, int length) { checkbounds(bytes, offset, length); char[] v = stringcoding.decode(bytes, offset, length); this.offset = 0; this.count = v.length; this.value = v; } /** * constructs a new {@code string} by decoding the specified array of bytes * using the platform's default charset. the length of the new {@code * string} is a function of the charset, and hence 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. the {@link * java.nio.charset.charsetdecoder} class should be used when more control * over the decoding process is required. * * @param bytes * the bytes to be decoded into characters * * @since jdk1.1 */ public string(byte bytes[]) { this(bytes, 0, bytes.length); } /** * allocates a new string that contains the sequence of characters * currently contained in the string buffer argument. the contents of the * string buffer are copied; subsequent modification of the string buffer * does not affect the newly created string. * * @param buffer * a {@code stringbuffer} */ public string(stringbuffer buffer) { string result = buffer.tostring(); this.value = result.value; this.count = result.count; this.offset = result.offset; } /** * 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 ease migration to {@code * stringbuilder}. obtaining a string from a string builder via the {@code * tostring} method is likely to run faster and is generally preferred. * * @param builder * a {@code stringbuilder} * * @since 1.5 */ public string(stringbuilder builder) { string result = builder.tostring(); this.value = result.value; this.count = result.count; this.offset = result.offset; } // package private constructor which shares value array for speed. string(int offset, int count, char value[]) { this.value = value; this.offset = offset; this.count = count; } /** * returns the length of this string. * the length is equal to the number of unicode * code units in the string. * * @return the length of the sequence of characters represented by this * object. */ public int length() { return count; } /** * returns true if, and only if, {@link #length()} is 0. * * @return true if {@link #length()} is 0, otherwise * false * * @since 1.6 */ public boolean isempty() { return count == 0; } /** * returns the char value at the * specified index. an index ranges from 0 to * length() - 1. the first char value of the sequence * is at index 0, the next at index 1, * and so on, as for array indexing. * *

if the char value specified by the index is a * surrogate, the surrogate * value is returned. * * @param index the index of the char value. * @return the char value at the specified index of this string. * the first char value is at index 0. * @exception indexoutofboundsexception if the index * argument is negative or not less than the length of this * string. */ public char charat(int index) { if ((index < 0) || (index >= count)) { throw new stringindexoutofboundsexception(index); } return value[index + offset]; } /** * returns the character (unicode code point) at the specified * index. the index refers to char values * (unicode code units) and ranges from 0 to * {@link #length()} - 1. * *

if the char value specified at the given index * is in the high-surrogate range, the following index is less * than the length of this string, and the * char value at the following index is in the * low-surrogate range, then the supplementary code point * corresponding to this surrogate pair is returned. otherwise, * the char value at the given index is returned. * * @param index the index to the char values * @return the code point value of the character at the * index * @exception indexoutofboundsexception if the index * argument is negative or not less than the length of this * string. * @since 1.5 */ public int codepointat(int index) { if ((index < 0) || (index >= count)) { throw new stringindexoutofboundsexception(index); } return character.codepointatimpl(value, offset + index, offset + count); } /** * returns the character (unicode code point) before the specified * index. the index refers to char values * (unicode code units) and ranges from 1 to {@link * charsequence#length() length}. * *

if the char value at (index - 1) * is in the low-surrogate range, (index - 2) is not * negative, and the char value at (index - * 2) is in the high-surrogate range, then the * supplementary code point value of the surrogate pair is * returned. if the char value at index - * 1 is an unpaired low-surrogate or a high-surrogate, the * surrogate value is returned. * * @param index the index following the code point that should be returned * @return the unicode code point value before the given index. * @exception indexoutofboundsexception if the index * argument is less than 1 or greater than the length * of this string. * @since 1.5 */ public int codepointbefore(int index) { int i = index - 1; if ((i < 0) || (i >= count)) { throw new stringindexoutofboundsexception(index); } return character.codepointbeforeimpl(value, offset + index, offset); } /** * returns the number of unicode code points in the specified text * range of this string. the text range begins at the * specified beginindex and extends to the * char at index endindex - 1. thus the * length (in chars) of the text range is * endindex-beginindex. unpaired surrogates within * the text range count as one code point each. * * @param beginindex the index to the first char of * the text range. * @param endindex the index after the last char of * the text range. * @return the number of unicode code points in the specified text * range * @exception indexoutofboundsexception if the * beginindex is negative, or endindex * is larger than the length of this string, or * beginindex is larger than endindex. * @since 1.5 */ public int codepointcount(int beginindex, int endindex) { if (beginindex < 0 || endindex > count || beginindex > endindex) { throw new indexoutofboundsexception(); } return character.codepointcountimpl(value, offset+beginindex, endindex-beginindex); } /** * returns the index within this string that is * offset from the given index by * codepointoffset code points. unpaired surrogates * within the text range given by index and * codepointoffset count as one code point each. * * @param index the index to be offset * @param codepointoffset the offset in code points * @return the index within this string * @exception indexoutofboundsexception if index * is negative or larger then the length of this * string, or if codepointoffset is positive * and the substring starting with index has fewer * than codepointoffset code points, * or if codepointoffset is negative and the substring * before index has fewer than the absolute value * of codepointoffset code points. * @since 1.5 */ public int offsetbycodepoints(int index, int codepointoffset) { if (index < 0 || index > count) { throw new indexoutofboundsexception(); } return character.offsetbycodepointsimpl(value, offset, count, offset+index, codepointoffset) - offset; } /** * copy characters from this string into dst starting at dstbegin. * this method doesn't perform any range checking. */ void getchars(char dst[], int dstbegin) { system.arraycopy(value, offset, dst, dstbegin, count); } /** * copies characters from this string into the destination character * array. *

* the first character to be copied is at index srcbegin; * the last character to be copied is at index srcend-1 * (thus the total number of characters to be copied is * srcend-srcbegin). the characters are copied into the * subarray of dst starting at index dstbegin * and ending at index: *

 

     *     dstbegin + (srcend-srcbegin) - 1
     * 
* * @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: *
  • srcbegin is negative. *
  • srcbegin is greater than srcend *
  • srcend is greater than the length of this * string *
  • dstbegin is negative *
  • dstbegin+(srcend-srcbegin) is larger than * dst.length
*/ public void getchars(int srcbegin, int srcend, char dst[], int dstbegin) { if (srcbegin < 0) { throw new stringindexoutofboundsexception(srcbegin); } if (srcend > count) { throw new stringindexoutofboundsexception(srcend); } if (srcbegin > srcend) { throw new stringindexoutofboundsexception(srcend - srcbegin); } system.arraycopy(value, offset + srcbegin, dst, dstbegin, srcend - srcbegin); } /** * 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 at index {@code srcbegin}; the * last character to be copied is at index {@code srcend-1}. the total * number of characters to be copied is {@code srcend-srcbegin}. the * characters, converted to bytes, are copied into the subarray of {@code * dst} starting at index {@code dstbegin} and ending at index: * *

     *     dstbegin + (srcend-srcbegin) - 1
     * 
* * @deprecated this method does not properly convert characters into * bytes. as of jdk 1.1, the preferred way to do this is via the * {@link #getbytes()} method, which uses the platform's default charset. * * @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 * * @throws indexoutofboundsexception * if any of the following is true: *
  • *
  • {@code srcbegin} is negative *
  • {@code srcbegin} is greater than {@code srcend} *
  • {@code srcend} is greater than the length of this string *
  • {@code dstbegin} is negative *
  • {@code dstbegin+(srcend-srcbegin)} is larger than {@code * dst.length} *
*/ @deprecated public void getbytes(int srcbegin, int srcend, byte dst[], int dstbegin) { if (srcbegin < 0) { throw new stringindexoutofboundsexception(srcbegin); } if (srcend > count) { throw new stringindexoutofboundsexception(srcend); } if (srcbegin > srcend) { throw new stringindexoutofboundsexception(srcend - srcbegin); } int j = dstbegin; int n = offset + srcend; int i = offset + srcbegin; char[] val = value; /* avoid getfield opcode */ while (i < n) { dst[j++] = (byte)val[i++]; } } /** * encodes this {@code string} into a sequence of bytes using the named * charset, storing the result into a new byte array. * *

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, offset, count); } /** * encodes this {@code string} into a sequence of bytes using the given * {@linkplain java.nio.charset.charset charset}, storing the result into a * new byte array. * *

this method always replaces malformed-input and unmappable-character * sequences with this charset's default replacement byte array. the * {@link java.nio.charset.charsetencoder} class should be used when more * control over the encoding process is required. * * @param charset * the {@linkplain java.nio.charset.charset} to be used to encode * the {@code string} * * @return the resultant byte array * * @since 1.6 */ public byte[] getbytes(charset charset) { if (charset == null) throw new nullpointerexception(); return stringcoding.encode(charset, value, offset, count); } /** * encodes this {@code string} into a sequence of bytes using the * platform's default charset, storing the result into a new byte array. * *

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, offset, count); } /** * 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 = count; if (n == anotherstring.count) { char v1[] = value; char v2[] = anotherstring.value; int i = offset; int j = anotherstring.offset; while (n-- != 0) { if (v1[i++] != v2[j++]) return false; } return true; } } return 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}. * * @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) { synchronized(sb) { return contentequals((charsequence)sb); } } /** * compares this string to the specified {@code charsequence}. the result * is {@code true} if and only if this {@code string} represents the same * sequence of char values as the specified sequence. * * @param cs * the sequence to compare this {@code string} against * * @return {@code true} if this {@code string} represents the same * sequence of char values as the specified sequence, {@code * false} otherwise * * @since 1.5 */ public boolean contentequals(charsequence cs) { if (count != cs.length()) return false; // argument is a stringbuffer, stringbuilder if (cs instanceof abstractstringbuilder) { char v1[] = value; char v2[] = ((abstractstringbuilder)cs).getvalue(); int i = offset; int j = 0; int n = count; while (n-- != 0) { if (v1[i++] != v2[j++]) return false; } } // argument is a string if (cs.equals(this)) return true; // argument is a generic charsequence char v1[] = value; int i = offset; int j = 0; int n = count; while (n-- != 0) { if (v1[i++] != cs.charat(j++)) return false; } return true; } /** * 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. * *

two characters {@code c1} and {@code c2} are considered the same * ignoring case if at least one of the following is true: *

  • *
  • the two characters are the same (as compared by the * {@code ==} operator) *
  • applying the method {@link * java.lang.character#touppercase(char)} to each character * produces the same result *
  • applying the method {@link * java.lang.character#tolowercase(char)} to each character * produces the same result *
* * @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.count == count) && regionmatches(true, 0, anotherstring, 0, count); } /** * compares two strings lexicographically. * the comparison is based on the unicode value of each character in * the strings. the character sequence represented by this * string object is compared lexicographically to the * character sequence represented by the argument string. the result is * a negative integer if this string object * lexicographically precedes the argument string. the result is a * positive integer if this string object lexicographically * follows the argument string. the result is zero if the strings * are equal; compareto returns 0 exactly when * the {@link #equals(object)} method would return true. *

* 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 k be the smallest such index; then the string * whose character at position k has the smaller value, as * determined by using the < operator, lexicographically precedes the * other string. in this case, compareto returns the * difference of the two character values at position k in * the two string -- that is, the value: *

     * this.charat(k)-anotherstring.charat(k)
     * 
* if there is no index position at which they differ, then the shorter * string lexicographically precedes the longer string. in this case, * compareto returns the difference of the lengths of the * strings -- that is, the value: *
     * this.length()-anotherstring.length()
     * 
* * @param anotherstring the string to be compared. * @return the value 0 if the argument string is equal to * this string; a value less than 0 if this string * is lexicographically less than the string argument; and a * value greater than 0 if this string is * lexicographically greater than the string argument. */ public int compareto(string anotherstring) { int len1 = count; int len2 = anotherstring.count; int n = math.min(len1, len2); char v1[] = value; char v2[] = anotherstring.value; int i = offset; int j = anotherstring.offset; if (i == j) { int k = i; int lim = n + i; while (k < lim) { char c1 = v1[k]; char c2 = v2[k]; if (c1 != c2) { return c1 - c2; } k++; } } else { while (n-- != 0) { char c1 = v1[i++]; char c2 = v2[j++]; if (c1 != c2) { return c1 - c2; } } } return len1 - len2; } /** * a comparator that orders string objects as by * comparetoignorecase. this comparator is serializable. *

* note that this comparator does not take locale into account, * and will result in an unsatisfactory ordering for certain locales. * the java.text package provides collators to allow * locale-sensitive ordering. * * @see java.text.collator#compare(string, string) * @since 1.2 */ public static final comparator case_insensitive_order = new caseinsensitivecomparator(); private static class caseinsensitivecomparator implements comparator, java.io.serializable { // use serialversionuid from jdk 1.2.2 for interoperability private static final long serialversionuid = 8575799808933029326l; public int compare(string s1, string s2) { int n1=s1.length(), n2=s2.length(); for (int i1=0, i2=0; i1compareto with normalized versions of the strings * where case differences have been eliminated by calling * character.tolowercase(character.touppercase(character)) on * each character. *

* note that this method does not take locale into account, * and will result in an unsatisfactory ordering for certain locales. * the java.text package provides collators to allow * locale-sensitive ordering. * * @param str the 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); } /** * tests if two string regions are equal. *

* a substring of this 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 * string object to be compared begins at index toffset * and has length len. the substring of other to be compared * begins at index ooffset and has length len. the * result is false if and only if at least one of the following * is true: *

  • toffset is negative. *
  • ooffset is negative. *
  • toffset+len is greater than the length of this * string object. *
  • ooffset+len is greater than the length of the other * argument. *
  • there is some nonnegative integer k less than len * such that: * this.charat(toffset+k) != other.charat(ooffset+k) *
* * @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 true if the specified subregion of this string * exactly matches the specified subregion of the string argument; * false otherwise. */ public boolean regionmatches(int toffset, string other, int ooffset, int len) { char ta[] = value; int to = offset + toffset; char pa[] = other.value; int po = other.offset + ooffset; // note: toffset, ooffset, or len might be near -1>>>1. if ((ooffset < 0) || (toffset < 0) || (toffset > (long)count - len) || (ooffset > (long)other.count - len)) { return false; } while (len-- > 0) { if (ta[to++] != pa[po++]) { return false; } } return true; } /** * tests if two string regions are equal. *

* a substring of this string object is compared to a substring * of the argument other. the result is true if these * substrings represent character sequences that are the same, ignoring * case if and only if ignorecase is true. the substring of * this string object to be compared begins at index * toffset and has length len. the substring of * other to be compared begins at index ooffset and * has length len. the result is false if and only if * at least one of the following is true: *

  • toffset is negative. *
  • ooffset is negative. *
  • toffset+len is greater than the length of this * string object. *
  • ooffset+len is greater than the length of the other * argument. *
  • ignorecase is false and there is some nonnegative * integer k less than len such that: *
         * this.charat(toffset+k) != other.charat(ooffset+k)
         * 
    *
  • ignorecase is true and there is some nonnegative * integer k less than len such that: *
         * character.tolowercase(this.charat(toffset+k)) !=
                   character.tolowercase(other.charat(ooffset+k))
         * 
    * and: *
         * character.touppercase(this.charat(toffset+k)) !=
         *         character.touppercase(other.charat(ooffset+k))
         * 
    *
* * @param ignorecase if 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 true if the specified subregion of this string * matches the specified subregion of the string argument; * false otherwise. whether the matching is exact * or case insensitive depends on the ignorecase * argument. */ public boolean regionmatches(boolean ignorecase, int toffset, string other, int ooffset, int len) { char ta[] = value; int to = offset + toffset; char pa[] = other.value; int po = other.offset + ooffset; // note: toffset, ooffset, or len might be near -1>>>1. if ((ooffset < 0) || (toffset < 0) || (toffset > (long)count - len) || (ooffset > (long)other.count - 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; } /** * 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 true if the character sequence represented by the * argument is a prefix of the substring of this object starting * at index toffset; false otherwise. * the result is false if toffset is * negative or greater than the length of this * string object; otherwise the result is the same * as the result of the expression *
     *          this.substring(toffset).startswith(prefix)
     *          
*/ public boolean startswith(string prefix, int toffset) { char ta[] = value; int to = offset + toffset; char pa[] = prefix.value; int po = prefix.offset; int pc = prefix.count; // note: toffset might be near -1>>>1. if ((toffset < 0) || (toffset > count - pc)) { return false; } while (--pc >= 0) { if (ta[to++] != pa[po++]) { return false; } } return true; } /** * tests if this string starts with the specified prefix. * * @param prefix the prefix. * @return true if the character sequence represented by the * argument is a prefix of the character sequence represented by * this string; false otherwise. * note also that true will be returned if the * argument is an empty string or is equal to this * string object as determined by the * {@link #equals(object)} method. * @since 1. 0 */ public boolean startswith(string prefix) { return startswith(prefix, 0); } /** * tests if this string ends with the specified suffix. * * @param suffix the suffix. * @return true if the character sequence represented by the * argument is a suffix of the character sequence represented by * this object; false otherwise. note that the * result will be true if the argument is the * empty string or is equal to this string object * as determined by the {@link #equals(object)} method. */ public boolean endswith(string suffix) { return startswith(suffix, count - suffix.count); } /** * returns a hash code for this string. the hash code for a * string object is computed as *
     * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
     * 
* using int arithmetic, where s[i] is the * ith character of the string, n is the length of * the string, and ^ 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) { int off = offset; char val[] = value; int len = count; for (int i = 0; i < len; i++) { h = 31*h + val[off++]; } hash = h; } return h; } /** * returns the index within this string of the first occurrence of * the specified character. if a character with value * ch occurs in the character sequence represented by * this string object, then the index (in unicode * code units) of the first such occurrence is returned. for * values of ch in the range from 0 to 0xffff * (inclusive), this is the smallest value k such that: *
     * this.charat(k) == ch
     * 
* is true. for other values of ch, it is the * smallest value k such that: *
     * this.codepointat(k) == ch
     * 
* is true. in either case, if no such character occurs in this * string, then -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 * -1 if the character does not occur. */ public int indexof(int ch) { return indexof(ch, 0); } /** * returns the index within this string of the first occurrence of the * specified character, starting the search at the specified index. *

* if a character with value ch occurs in the * character sequence represented by this string * object at an index no smaller than fromindex, then * the index of the first such occurrence is returned. for values * of ch in the range from 0 to 0xffff (inclusive), * this is the smallest value k such that: *

     * (this.charat(k) == ch) && (k >= fromindex)
     * 
* is true. for other values of ch, it is the * smallest value k such that: *
     * (this.codepointat(k) == ch) && (k >= fromindex)
     * 
* is true. in either case, if no such character occurs in this * string at or after position fromindex, then * -1 is returned. * *

* there is no restriction on the value of 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: -1 is returned. * *

all indices are specified in 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 fromindex, or -1 * if the character does not occur. */ public int indexof(int ch, int fromindex) { int max = offset + count; char v[] = value; if (fromindex < 0) { fromindex = 0; } else if (fromindex >= count) { // note: fromindex might be near -1>>>1. return -1; } int i = offset + 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)) for (; i < max ; i++) { if (v[i] == ch) { return i - offset; } } return -1; } if (ch <= character.max_code_point) { // handle supplementary characters here char[] surrogates = character.tochars(ch); for (; i < max; i++) { if (v[i] == surrogates[0]) { if (i + 1 == max) { break; } if (v[i+1] == surrogates[1]) { return i - offset; } } } } return -1; } /** * returns the index within this string of the last occurrence of * the specified character. for values of ch in the * range from 0 to 0xffff (inclusive), the index (in unicode code * units) returned is the largest value k such that: *

     * this.charat(k) == ch
     * 
* is true. for other values of ch, it is the * largest value k such that: *
     * this.codepointat(k) == ch
     * 
* is true. in either case, if no such character occurs in this * string, then -1 is returned. the * 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 * -1 if the character does not occur. */ public int lastindexof(int ch) { return lastindexof(ch, count - 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 ch in the range * from 0 to 0xffff (inclusive), the index returned is the largest * value k such that: *
     * (this.charat(k) == ch) && (k <= fromindex)
     * 
* is true. for other values of ch, it is the * largest value k such that: *
     * (this.codepointat(k) == ch) && (k <= fromindex)
     * 
* is true. in either case, if no such character occurs in this * string at or before position fromindex, then * -1 is returned. * *

all indices are specified in 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 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 fromindex, or -1 * if the character does not occur before that point. */ public int lastindexof(int ch, int fromindex) { int min = offset; char v[] = value; int i = offset + ((fromindex >= count) ? count - 1 : 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)) for (; i >= min ; i--) { if (v[i] == ch) { return i - offset; } } return -1; } int max = offset + count; if (ch <= character.max_code_point) { // handle supplementary characters here char[] surrogates = character.tochars(ch); for (; i >= min; i--) { if (v[i] == surrogates[0]) { if (i + 1 == max) { break; } if (v[i+1] == surrogates[1]) { return i - offset; } } } } return -1; } /** * returns the index within this string of the first occurrence of the * specified substring. the integer returned is the smallest value * k such that: *

     * this.startswith(str, k)
     * 
* is true. * * @param str any string. * @return if the string argument occurs as a substring within this * object, then the index of the first character of the first * such substring is returned; if it does not occur as a * substring, -1 is returned. */ public int indexof(string str) { return indexof(str, 0); } /** * returns the index within this string of the first occurrence of the * specified substring, starting at the specified index. the integer * returned is the smallest value k for which: *
     *     k >= math.min(fromindex, this.length()) && this.startswith(str, k)
     * 
* if no such value of k exists, then -1 is returned. * * @param str the substring for which to search. * @param fromindex the index from which to start the search. * @return the index within this string of the first occurrence of the * specified substring, starting at the specified index. */ public int indexof(string str, int fromindex) { return indexof(value, offset, count, str.value, str.offset, str.count, fromindex); } /** * code shared by string and stringbuffer to do searches. the * source is the character array being searched, and the target * is the string being searched for. * * @param source the characters being searched. * @param sourceoffset offset of the source string. * @param sourcecount count of the source string. * @param target the characters being searched for. * @param targetoffset offset of the target string. * @param targetcount count of the target string. * @param fromindex the index to begin searching from. */ static int indexof(char[] source, int sourceoffset, int sourcecount, char[] target, int targetoffset, int targetcount, int fromindex) { if (fromindex >= sourcecount) { return (targetcount == 0 ? sourcecount : -1); } if (fromindex < 0) { fromindex = 0; } if (targetcount == 0) { return fromindex; } char first = target[targetoffset]; int max = sourceoffset + (sourcecount - targetcount); for (int i = sourceoffset + fromindex; i <= max; i++) { /* look for first character. */ if (source[i] != first) { while (++i <= max && source[i] != first); } /* found first character, now look at the rest of v2 */ if (i <= max) { int j = i + 1; int end = j + targetcount - 1; for (int k = targetoffset + 1; j < end && source[j] == target[k]; j++, k++); if (j == end) { /* found whole string. */ return i - sourceoffset; } } } return -1; } /** * returns the index within this string of the rightmost occurrence * of the specified substring. the rightmost empty string "" is * considered to occur at the index value this.length(). * the returned index is the largest value k such that *
     * this.startswith(str, k)
     * 
* is true. * * @param str the substring to search for. * @return if the string argument occurs one or more times as a substring * within this object, then the index of the first character of * the last such substring is returned. if it does not occur as * a substring, -1 is returned. */ public int lastindexof(string str) { return lastindexof(str, count); } /** * returns the index within this string of the last occurrence of the * specified substring, searching backward starting at the specified index. * the integer returned is the largest value k such that: *
     *     k <= math.min(fromindex, this.length()) && this.startswith(str, k)
     * 
* if no such value of k exists, then -1 is returned. * * @param str the substring to search for. * @param fromindex the index to start the search from. * @return the index within this string of the last occurrence of the * specified substring. */ public int lastindexof(string str, int fromindex) { return lastindexof(value, offset, count, str.value, str.offset, str.count, fromindex); } /** * code shared by string and stringbuffer to do searches. the * source is the character array being searched, and the target * is the string being searched for. * * @param source the characters being searched. * @param sourceoffset offset of the source string. * @param sourcecount count of the source string. * @param target the characters being searched for. * @param targetoffset offset of the target string. * @param targetcount count of the target string. * @param fromindex the index to begin searching from. */ static int lastindexof(char[] source, int sourceoffset, int sourcecount, char[] target, int targetoffset, int targetcount, int fromindex) { /* * check arguments; return immediately where possible. for * consistency, don't check for null str. */ int rightindex = sourcecount - targetcount; if (fromindex < 0) { return -1; } if (fromindex > rightindex) { fromindex = rightindex; } /* empty string always matches. */ if (targetcount == 0) { return fromindex; } int strlastindex = targetoffset + targetcount - 1; char strlastchar = target[strlastindex]; int min = sourceoffset + targetcount - 1; int i = min + fromindex; startsearchforlastchar: while (true) { while (i >= min && source[i] != strlastchar) { i--; } if (i < min) { return -1; } int j = i - 1; int start = j - (targetcount - 1); int k = strlastindex - 1; while (j > start) { if (source[j--] != target[k--]) { i--; continue startsearchforlastchar; } } return start - sourceoffset + 1; } } /** * returns a new 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.

* examples: *

     * "unhappy".substring(2) returns "happy"
     * "harbison".substring(3) returns "bison"
     * "emptiness".substring(9) returns "" (an empty string)
     * 
* * @param beginindex the beginning index, inclusive. * @return the specified substring. * @exception indexoutofboundsexception if * beginindex is negative or larger than the * length of this string object. */ public string substring(int beginindex) { return substring(beginindex, count); } /** * returns a new string that is a substring of this string. the * substring begins at the specified beginindex and * extends to the character at index endindex - 1. * thus the length of the substring is endindex-beginindex. *

* examples: *

     * "hamburger".substring(4, 8) returns "urge"
     * "smiles".substring(1, 5) returns "mile"
     * 
* * @param beginindex the beginning index, inclusive. * @param endindex the ending index, exclusive. * @return the specified substring. * @exception indexoutofboundsexception if the * beginindex is negative, or * endindex is larger than the length of * this string object, or * beginindex is larger than * endindex. */ public string substring(int beginindex, int endindex) { if (beginindex < 0) { throw new stringindexoutofboundsexception(beginindex); } if (endindex > count) { throw new stringindexoutofboundsexception(endindex); } if (beginindex > endindex) { throw new stringindexoutofboundsexception(endindex - beginindex); } return ((beginindex == 0) && (endindex == count)) ? this : new string(offset + beginindex, endindex - beginindex, value); } /** * returns a new character sequence that is a subsequence of this sequence. * *

an invocation of this method of the form * *

     * str.subsequence(begin, end)
* * behaves in exactly the same way as the invocation * *
     * str.substring(begin, end)
* * this method is defined so that the 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 beginindex or endindex are negative, * if endindex is greater than length(), * or if beginindex is greater than startindex * * @since 1.4 * @spec jsr-51 */ public charsequence subsequence(int beginindex, int endindex) { return this.substring(beginindex, endindex); } /** * concatenates the specified string to the end of this string. *

* if the length of the argument string is 0, then this * string object is returned. otherwise, a new * string object is created, representing a character * sequence that is the concatenation of the character sequence * represented by this string object and the character * sequence represented by the argument string.

* examples: *

     * "cares".concat("s") returns "caress"
     * "to".concat("get").concat("her") returns "together"
     * 
* * @param str the string that is concatenated to the end * of this 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) { int otherlen = str.length(); if (otherlen == 0) { return this; } char buf[] = new char[count + otherlen]; getchars(0, count, buf, 0); str.getchars(0, otherlen, buf, count); return new string(0, count + otherlen, buf); } /** * returns a new string resulting from replacing all occurrences of * oldchar in this string with newchar. *

* if the character oldchar does not occur in the * character sequence represented by this string object, * then a reference to this string object is returned. * otherwise, a new string object is created that * represents a character sequence identical to the character sequence * represented by this string object, except that every * occurrence of oldchar is replaced by an occurrence * of newchar. *

* examples: *

     * "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)
     * 
* * @param oldchar the old character. * @param newchar the new character. * @return a string derived from this string by replacing every * occurrence of oldchar with newchar. */ public string replace(char oldchar, char newchar) { if (oldchar != newchar) { int len = count; int i = -1; char[] val = value; /* avoid getfield opcode */ int off = offset; /* avoid getfield opcode */ while (++i < len) { if (val[off + i] == oldchar) { break; } } if (i < len) { char buf[] = new char[len]; for (int j = 0 ; j < i ; j++) { buf[j] = val[off+j]; } while (i < len) { char c = val[off + i]; buf[i] = (c == oldchar) ? newchar : c; i++; } return new string(0, len, buf); } } return this; } /** * tells whether or not this string matches the given regular expression. * *

an invocation of this method of the form * str.matches(regex) yields exactly the * same result as the expression * *

{@link java.util.regex.pattern}.{@link * java.util.regex.pattern#matches(string,charsequence) * matches}(regex, str)
* * @param regex * the regular expression to which this string is to be matched * * @return true