2 * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
28 import java.io.UnsupportedEncodingException;
29 import java.util.Comparator;
32 * The <code>String</code> class represents character strings. All
33 * string literals in Java programs, such as <code>"abc"</code>, are
34 * implemented as instances of this class.
36 * Strings are constant; their values cannot be changed after they
37 * are created. String buffers support mutable strings.
38 * Because String objects are immutable they can be shared. For example:
39 * <p><blockquote><pre>
41 * </pre></blockquote><p>
43 * <p><blockquote><pre>
44 * char data[] = {'a', 'b', 'c'};
45 * String str = new String(data);
46 * </pre></blockquote><p>
47 * Here are some more examples of how strings can be used:
48 * <p><blockquote><pre>
49 * System.out.println("abc");
51 * System.out.println("abc" + cde);
52 * String c = "abc".substring(2,3);
53 * String d = cde.substring(1, 2);
56 * The class <code>String</code> includes methods for examining
57 * individual characters of the sequence, for comparing strings, for
58 * searching strings, for extracting substrings, and for creating a
59 * copy of a string with all characters translated to uppercase or to
60 * lowercase. Case mapping is based on the Unicode Standard version
61 * specified by the {@link java.lang.Character Character} class.
63 * The Java language provides special support for the string
64 * concatenation operator ( + ), and for conversion of
65 * other objects to strings. String concatenation is implemented
66 * through the <code>StringBuilder</code>(or <code>StringBuffer</code>)
67 * class and its <code>append</code> method.
68 * String conversions are implemented through the method
69 * <code>toString</code>, defined by <code>Object</code> and
70 * inherited by all classes in Java. For additional information on
71 * string concatenation and conversion, see Gosling, Joy, and Steele,
72 * <i>The Java Language Specification</i>.
74 * <p> Unless otherwise noted, passing a <tt>null</tt> argument to a constructor
75 * or method in this class will cause a {@link NullPointerException} to be
78 * <p>A <code>String</code> represents a string in the UTF-16 format
79 * in which <em>supplementary characters</em> are represented by <em>surrogate
80 * pairs</em> (see the section <a href="Character.html#unicode">Unicode
81 * Character Representations</a> in the <code>Character</code> class for
83 * Index values refer to <code>char</code> code units, so a supplementary
84 * character uses two positions in a <code>String</code>.
85 * <p>The <code>String</code> class provides methods for dealing with
86 * Unicode code points (i.e., characters), in addition to those for
87 * dealing with Unicode code units (i.e., <code>char</code> values).
90 * @author Arthur van Hoff
91 * @author Martin Buchholz
93 * @see java.lang.Object#toString()
94 * @see java.lang.StringBuffer
95 * @see java.lang.StringBuilder
96 * @see java.nio.charset.Charset
100 public final class String
101 implements java.io.Serializable, Comparable<String>, CharSequence
103 /** The value is used for character storage. */
104 private final char value[];
106 /** The offset is the first index of the storage that is used. */
107 private final int offset;
109 /** The count is the number of characters in the String. */
110 private final int count;
112 /** Cache the hash code for the string */
113 private int hash; // Default to 0
115 /** use serialVersionUID from JDK 1.0.2 for interoperability */
116 private static final long serialVersionUID = -6849794470754667710L;
119 * Class String is special cased within the Serialization Stream Protocol.
121 * A String instance is written initially into an ObjectOutputStream in the
124 * <code>TC_STRING</code> (utf String)
126 * The String is written by method <code>DataOutput.writeUTF</code>.
127 * A new handle is generated to refer to all future references to the
128 * string instance within the stream.
130 // private static final ObjectStreamField[] serialPersistentFields =
131 // new ObjectStreamField[0];
134 * Initializes a newly created {@code String} object so that it represents
135 * an empty character sequence. Note that use of this constructor is
136 * unnecessary since Strings are immutable.
141 this.value = new char[0];
145 * Initializes a newly created {@code String} object so that it represents
146 * the same sequence of characters as the argument; in other words, the
147 * newly created string is a copy of the argument string. Unless an
148 * explicit copy of {@code original} is needed, use of this constructor is
149 * unnecessary since Strings are immutable.
154 public String(String original) {
155 int size = original.count;
156 char[] originalValue = original.value;
158 if (originalValue.length > size) {
159 // The array representing the String is bigger than the new
160 // String itself. Perhaps this constructor is being called
161 // in order to trim the baggage, so make a copy of the array.
162 int off = original.offset;
163 v = copyOfRange(originalValue, off, off+size);
165 // The array representing the String is the same
166 // size as the String, so no point in making a copy.
175 * Allocates a new {@code String} so that it represents the sequence of
176 * characters currently contained in the character array argument. The
177 * contents of the character array are copied; subsequent modification of
178 * the character array does not affect the newly created string.
181 * The initial value of the string
183 public String(char value[]) {
184 int size = value.length;
187 this.value = copyOf(value, size);
191 * Allocates a new {@code String} that contains characters from a subarray
192 * of the character array argument. The {@code offset} argument is the
193 * index of the first character of the subarray and the {@code count}
194 * argument specifies the length of the subarray. The contents of the
195 * subarray are copied; subsequent modification of the character array does
196 * not affect the newly created string.
199 * Array that is the source of characters
207 * @throws IndexOutOfBoundsException
208 * If the {@code offset} and {@code count} arguments index
209 * characters outside the bounds of the {@code value} array
211 public String(char value[], int offset, int count) {
213 throw new StringIndexOutOfBoundsException(offset);
216 throw new StringIndexOutOfBoundsException(count);
218 // Note: offset or count might be near -1>>>1.
219 if (offset > value.length - count) {
220 throw new StringIndexOutOfBoundsException(offset + count);
224 this.value = copyOfRange(value, offset, offset+count);
228 * Allocates a new {@code String} that contains characters from a subarray
229 * of the <a href="Character.html#unicode">Unicode code point</a> array
230 * argument. The {@code offset} argument is the index of the first code
231 * point of the subarray and the {@code count} argument specifies the
232 * length of the subarray. The contents of the subarray are converted to
233 * {@code char}s; subsequent modification of the {@code int} array does not
234 * affect the newly created string.
237 * Array that is the source of Unicode code points
245 * @throws IllegalArgumentException
246 * If any invalid Unicode code point is found in {@code
249 * @throws IndexOutOfBoundsException
250 * If the {@code offset} and {@code count} arguments index
251 * characters outside the bounds of the {@code codePoints} array
255 public String(int[] codePoints, int offset, int count) {
257 throw new StringIndexOutOfBoundsException(offset);
260 throw new StringIndexOutOfBoundsException(count);
262 // Note: offset or count might be near -1>>>1.
263 if (offset > codePoints.length - count) {
264 throw new StringIndexOutOfBoundsException(offset + count);
267 final int end = offset + count;
269 // Pass 1: Compute precise size of char[]
271 for (int i = offset; i < end; i++) {
272 int c = codePoints[i];
273 if (Character.isBmpCodePoint(c))
275 else if (Character.isValidCodePoint(c))
277 else throw new IllegalArgumentException(Integer.toString(c));
280 // Pass 2: Allocate and fill in char[]
281 final char[] v = new char[n];
283 for (int i = offset, j = 0; i < end; i++, j++) {
284 int c = codePoints[i];
285 if (Character.isBmpCodePoint(c))
288 Character.toSurrogates(c, v, j++);
297 * Allocates a new {@code String} constructed from a subarray of an array
298 * of 8-bit integer values.
300 * <p> The {@code offset} argument is the index of the first byte of the
301 * subarray, and the {@code count} argument specifies the length of the
304 * <p> Each {@code byte} in the subarray is converted to a {@code char} as
305 * specified in the method above.
307 * @deprecated This method does not properly convert bytes into characters.
308 * As of JDK 1.1, the preferred way to do this is via the
309 * {@code String} constructors that take a {@link
310 * java.nio.charset.Charset}, charset name, or that use the platform's
314 * The bytes to be converted to characters
317 * The top 8 bits of each 16-bit Unicode code unit
324 * @throws IndexOutOfBoundsException
325 * If the {@code offset} or {@code count} argument is invalid
327 * @see #String(byte[], int)
328 * @see #String(byte[], int, int, java.lang.String)
329 * @see #String(byte[], int, int, java.nio.charset.Charset)
330 * @see #String(byte[], int, int)
331 * @see #String(byte[], java.lang.String)
332 * @see #String(byte[], java.nio.charset.Charset)
333 * @see #String(byte[])
336 public String(byte ascii[], int hibyte, int offset, int count) {
337 checkBounds(ascii, offset, count);
338 char value[] = new char[count];
341 for (int i = count ; i-- > 0 ;) {
342 value[i] = (char) (ascii[i + offset] & 0xff);
346 for (int i = count ; i-- > 0 ;) {
347 value[i] = (char) (hibyte | (ascii[i + offset] & 0xff));
356 * Allocates a new {@code String} containing characters constructed from
357 * an array of 8-bit integer values. Each character <i>c</i>in the
358 * resulting string is constructed from the corresponding component
359 * <i>b</i> in the byte array such that:
362 * <b><i>c</i></b> == (char)(((hibyte & 0xff) << 8)
363 * | (<b><i>b</i></b> & 0xff))
364 * </pre></blockquote>
366 * @deprecated This method does not properly convert bytes into
367 * characters. As of JDK 1.1, the preferred way to do this is via the
368 * {@code String} constructors that take a {@link
369 * java.nio.charset.Charset}, charset name, or that use the platform's
373 * The bytes to be converted to characters
376 * The top 8 bits of each 16-bit Unicode code unit
378 * @see #String(byte[], int, int, java.lang.String)
379 * @see #String(byte[], int, int, java.nio.charset.Charset)
380 * @see #String(byte[], int, int)
381 * @see #String(byte[], java.lang.String)
382 * @see #String(byte[], java.nio.charset.Charset)
383 * @see #String(byte[])
386 public String(byte ascii[], int hibyte) {
387 this(ascii, hibyte, 0, ascii.length);
390 /* Common private utility method used to bounds check the byte array
391 * and requested offset & length values used by the String(byte[],..)
394 private static void checkBounds(byte[] bytes, int offset, int length) {
396 throw new StringIndexOutOfBoundsException(length);
398 throw new StringIndexOutOfBoundsException(offset);
399 if (offset > bytes.length - length)
400 throw new StringIndexOutOfBoundsException(offset + length);
404 * Constructs a new {@code String} by decoding the specified subarray of
405 * bytes using the specified charset. The length of the new {@code String}
406 * is a function of the charset, and hence may not be equal to the length
409 * <p> The behavior of this constructor when the given bytes are not valid
410 * in the given charset is unspecified. The {@link
411 * java.nio.charset.CharsetDecoder} class should be used when more control
412 * over the decoding process is required.
415 * The bytes to be decoded into characters
418 * The index of the first byte to decode
421 * The number of bytes to decode
424 * The name of a supported {@linkplain java.nio.charset.Charset
427 * @throws UnsupportedEncodingException
428 * If the named charset is not supported
430 * @throws IndexOutOfBoundsException
431 * If the {@code offset} and {@code length} arguments index
432 * characters outside the bounds of the {@code bytes} array
436 public String(byte bytes[], int offset, int length, String charsetName)
437 throws UnsupportedEncodingException
439 if (charsetName == null)
440 throw new NullPointerException("charsetName");
441 checkBounds(bytes, offset, length);
442 char[] v = StringCoding.decode(charsetName, bytes, offset, length);
444 this.count = v.length;
449 * Constructs a new {@code String} by decoding the specified subarray of
450 * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
451 * The length of the new {@code String} is a function of the charset, and
452 * hence may not be equal to the length of the subarray.
454 * <p> This method always replaces malformed-input and unmappable-character
455 * sequences with this charset's default replacement string. The {@link
456 * java.nio.charset.CharsetDecoder} class should be used when more control
457 * over the decoding process is required.
460 * The bytes to be decoded into characters
463 * The index of the first byte to decode
466 * The number of bytes to decode
469 * The {@linkplain java.nio.charset.Charset charset} to be used to
470 * decode the {@code bytes}
472 * @throws IndexOutOfBoundsException
473 * If the {@code offset} and {@code length} arguments index
474 * characters outside the bounds of the {@code bytes} array
478 /* don't want dependnecy on Charset
479 public String(byte bytes[], int offset, int length, Charset charset) {
481 throw new NullPointerException("charset");
482 checkBounds(bytes, offset, length);
483 char[] v = StringCoding.decode(charset, bytes, offset, length);
485 this.count = v.length;
491 * Constructs a new {@code String} by decoding the specified array of bytes
492 * using the specified {@linkplain java.nio.charset.Charset charset}. The
493 * length of the new {@code String} is a function of the charset, and hence
494 * may not be equal to the length of the byte array.
496 * <p> The behavior of this constructor when the given bytes are not valid
497 * in the given charset is unspecified. The {@link
498 * java.nio.charset.CharsetDecoder} class should be used when more control
499 * over the decoding process is required.
502 * The bytes to be decoded into characters
505 * The name of a supported {@linkplain java.nio.charset.Charset
508 * @throws UnsupportedEncodingException
509 * If the named charset is not supported
513 public String(byte bytes[], String charsetName)
514 throws UnsupportedEncodingException
516 this(bytes, 0, bytes.length, charsetName);
520 * Constructs a new {@code String} by decoding the specified array of
521 * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
522 * The length of the new {@code String} is a function of the charset, and
523 * hence may not be equal to the length of the byte array.
525 * <p> This method always replaces malformed-input and unmappable-character
526 * sequences with this charset's default replacement string. The {@link
527 * java.nio.charset.CharsetDecoder} class should be used when more control
528 * over the decoding process is required.
531 * The bytes to be decoded into characters
534 * The {@linkplain java.nio.charset.Charset charset} to be used to
535 * decode the {@code bytes}
539 /* don't want dep on Charset
540 public String(byte bytes[], Charset charset) {
541 this(bytes, 0, bytes.length, charset);
546 * Constructs a new {@code String} by decoding the specified subarray of
547 * bytes using the platform's default charset. The length of the new
548 * {@code String} is a function of the charset, and hence may not be equal
549 * to the length of the subarray.
551 * <p> The behavior of this constructor when the given bytes are not valid
552 * in the default charset is unspecified. The {@link
553 * java.nio.charset.CharsetDecoder} class should be used when more control
554 * over the decoding process is required.
557 * The bytes to be decoded into characters
560 * The index of the first byte to decode
563 * The number of bytes to decode
565 * @throws IndexOutOfBoundsException
566 * If the {@code offset} and the {@code length} arguments index
567 * characters outside the bounds of the {@code bytes} array
571 public String(byte bytes[], int offset, int length) {
572 checkBounds(bytes, offset, length);
573 char[] v = StringCoding.decode(bytes, offset, length);
575 this.count = v.length;
580 * Constructs a new {@code String} by decoding the specified array of bytes
581 * using the platform's default charset. The length of the new {@code
582 * String} is a function of the charset, and hence may not be equal to the
583 * length of the byte array.
585 * <p> The behavior of this constructor when the given bytes are not valid
586 * in the default charset is unspecified. The {@link
587 * java.nio.charset.CharsetDecoder} class should be used when more control
588 * over the decoding process is required.
591 * The bytes to be decoded into characters
595 public String(byte bytes[]) {
596 this(bytes, 0, bytes.length);
600 * Allocates a new string that contains the sequence of characters
601 * currently contained in the string buffer argument. The contents of the
602 * string buffer are copied; subsequent modification of the string buffer
603 * does not affect the newly created string.
606 * A {@code StringBuffer}
608 public String(StringBuffer buffer) {
609 String result = buffer.toString();
610 this.value = result.value;
611 this.count = result.count;
612 this.offset = result.offset;
616 * Allocates a new string that contains the sequence of characters
617 * currently contained in the string builder argument. The contents of the
618 * string builder are copied; subsequent modification of the string builder
619 * does not affect the newly created string.
621 * <p> This constructor is provided to ease migration to {@code
622 * StringBuilder}. Obtaining a string from a string builder via the {@code
623 * toString} method is likely to run faster and is generally preferred.
626 * A {@code StringBuilder}
630 public String(StringBuilder builder) {
631 String result = builder.toString();
632 this.value = result.value;
633 this.count = result.count;
634 this.offset = result.offset;
638 // Package private constructor which shares value array for speed.
639 String(int offset, int count, char value[]) {
641 this.offset = offset;
646 * Returns the length of this string.
647 * The length is equal to the number of <a href="Character.html#unicode">Unicode
648 * code units</a> in the string.
650 * @return the length of the sequence of characters represented by this
653 public int length() {
658 * Returns <tt>true</tt> if, and only if, {@link #length()} is <tt>0</tt>.
660 * @return <tt>true</tt> if {@link #length()} is <tt>0</tt>, otherwise
665 public boolean isEmpty() {
670 * Returns the <code>char</code> value at the
671 * specified index. An index ranges from <code>0</code> to
672 * <code>length() - 1</code>. The first <code>char</code> value of the sequence
673 * is at index <code>0</code>, the next at index <code>1</code>,
674 * and so on, as for array indexing.
676 * <p>If the <code>char</code> value specified by the index is a
677 * <a href="Character.html#unicode">surrogate</a>, the surrogate
680 * @param index the index of the <code>char</code> value.
681 * @return the <code>char</code> value at the specified index of this string.
682 * The first <code>char</code> value is at index <code>0</code>.
683 * @exception IndexOutOfBoundsException if the <code>index</code>
684 * argument is negative or not less than the length of this
687 public char charAt(int index) {
688 if ((index < 0) || (index >= count)) {
689 throw new StringIndexOutOfBoundsException(index);
691 return value[index + offset];
695 * Returns the character (Unicode code point) at the specified
696 * index. The index refers to <code>char</code> values
697 * (Unicode code units) and ranges from <code>0</code> to
698 * {@link #length()}<code> - 1</code>.
700 * <p> If the <code>char</code> value specified at the given index
701 * is in the high-surrogate range, the following index is less
702 * than the length of this <code>String</code>, and the
703 * <code>char</code> value at the following index is in the
704 * low-surrogate range, then the supplementary code point
705 * corresponding to this surrogate pair is returned. Otherwise,
706 * the <code>char</code> value at the given index is returned.
708 * @param index the index to the <code>char</code> values
709 * @return the code point value of the character at the
711 * @exception IndexOutOfBoundsException if the <code>index</code>
712 * argument is negative or not less than the length of this
716 public int codePointAt(int index) {
717 if ((index < 0) || (index >= count)) {
718 throw new StringIndexOutOfBoundsException(index);
720 return Character.codePointAtImpl(value, offset + index, offset + count);
724 * Returns the character (Unicode code point) before the specified
725 * index. The index refers to <code>char</code> values
726 * (Unicode code units) and ranges from <code>1</code> to {@link
727 * CharSequence#length() length}.
729 * <p> If the <code>char</code> value at <code>(index - 1)</code>
730 * is in the low-surrogate range, <code>(index - 2)</code> is not
731 * negative, and the <code>char</code> value at <code>(index -
732 * 2)</code> is in the high-surrogate range, then the
733 * supplementary code point value of the surrogate pair is
734 * returned. If the <code>char</code> value at <code>index -
735 * 1</code> is an unpaired low-surrogate or a high-surrogate, the
736 * surrogate value is returned.
738 * @param index the index following the code point that should be returned
739 * @return the Unicode code point value before the given index.
740 * @exception IndexOutOfBoundsException if the <code>index</code>
741 * argument is less than 1 or greater than the length
745 public int codePointBefore(int index) {
747 if ((i < 0) || (i >= count)) {
748 throw new StringIndexOutOfBoundsException(index);
750 return Character.codePointBeforeImpl(value, offset + index, offset);
754 * Returns the number of Unicode code points in the specified text
755 * range of this <code>String</code>. The text range begins at the
756 * specified <code>beginIndex</code> and extends to the
757 * <code>char</code> at index <code>endIndex - 1</code>. Thus the
758 * length (in <code>char</code>s) of the text range is
759 * <code>endIndex-beginIndex</code>. Unpaired surrogates within
760 * the text range count as one code point each.
762 * @param beginIndex the index to the first <code>char</code> of
764 * @param endIndex the index after the last <code>char</code> of
766 * @return the number of Unicode code points in the specified text
768 * @exception IndexOutOfBoundsException if the
769 * <code>beginIndex</code> is negative, or <code>endIndex</code>
770 * is larger than the length of this <code>String</code>, or
771 * <code>beginIndex</code> is larger than <code>endIndex</code>.
774 public int codePointCount(int beginIndex, int endIndex) {
775 if (beginIndex < 0 || endIndex > count || beginIndex > endIndex) {
776 throw new IndexOutOfBoundsException();
778 return Character.codePointCountImpl(value, offset+beginIndex, endIndex-beginIndex);
782 * Returns the index within this <code>String</code> that is
783 * offset from the given <code>index</code> by
784 * <code>codePointOffset</code> code points. Unpaired surrogates
785 * within the text range given by <code>index</code> and
786 * <code>codePointOffset</code> count as one code point each.
788 * @param index the index to be offset
789 * @param codePointOffset the offset in code points
790 * @return the index within this <code>String</code>
791 * @exception IndexOutOfBoundsException if <code>index</code>
792 * is negative or larger then the length of this
793 * <code>String</code>, or if <code>codePointOffset</code> is positive
794 * and the substring starting with <code>index</code> has fewer
795 * than <code>codePointOffset</code> code points,
796 * or if <code>codePointOffset</code> is negative and the substring
797 * before <code>index</code> has fewer than the absolute value
798 * of <code>codePointOffset</code> code points.
801 public int offsetByCodePoints(int index, int codePointOffset) {
802 if (index < 0 || index > count) {
803 throw new IndexOutOfBoundsException();
805 return Character.offsetByCodePointsImpl(value, offset, count,
806 offset+index, codePointOffset) - offset;
810 * Copy characters from this string into dst starting at dstBegin.
811 * This method doesn't perform any range checking.
813 void getChars(char dst[], int dstBegin) {
814 System.arraycopy(value, offset, dst, dstBegin, count);
818 * Copies characters from this string into the destination character
821 * The first character to be copied is at index <code>srcBegin</code>;
822 * the last character to be copied is at index <code>srcEnd-1</code>
823 * (thus the total number of characters to be copied is
824 * <code>srcEnd-srcBegin</code>). The characters are copied into the
825 * subarray of <code>dst</code> starting at index <code>dstBegin</code>
826 * and ending at index:
827 * <p><blockquote><pre>
828 * dstbegin + (srcEnd-srcBegin) - 1
829 * </pre></blockquote>
831 * @param srcBegin index of the first character in the string
833 * @param srcEnd index after the last character in the string
835 * @param dst the destination array.
836 * @param dstBegin the start offset in the destination array.
837 * @exception IndexOutOfBoundsException If any of the following
839 * <ul><li><code>srcBegin</code> is negative.
840 * <li><code>srcBegin</code> is greater than <code>srcEnd</code>
841 * <li><code>srcEnd</code> is greater than the length of this
843 * <li><code>dstBegin</code> is negative
844 * <li><code>dstBegin+(srcEnd-srcBegin)</code> is larger than
845 * <code>dst.length</code></ul>
847 public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
849 throw new StringIndexOutOfBoundsException(srcBegin);
851 if (srcEnd > count) {
852 throw new StringIndexOutOfBoundsException(srcEnd);
854 if (srcBegin > srcEnd) {
855 throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
857 System.arraycopy(value, offset + srcBegin, dst, dstBegin,
862 * Copies characters from this string into the destination byte array. Each
863 * byte receives the 8 low-order bits of the corresponding character. The
864 * eight high-order bits of each character are not copied and do not
865 * participate in the transfer in any way.
867 * <p> The first character to be copied is at index {@code srcBegin}; the
868 * last character to be copied is at index {@code srcEnd-1}. The total
869 * number of characters to be copied is {@code srcEnd-srcBegin}. The
870 * characters, converted to bytes, are copied into the subarray of {@code
871 * dst} starting at index {@code dstBegin} and ending at index:
874 * dstbegin + (srcEnd-srcBegin) - 1
875 * </pre></blockquote>
877 * @deprecated This method does not properly convert characters into
878 * bytes. As of JDK 1.1, the preferred way to do this is via the
879 * {@link #getBytes()} method, which uses the platform's default charset.
882 * Index of the first character in the string to copy
885 * Index after the last character in the string to copy
888 * The destination array
891 * The start offset in the destination array
893 * @throws IndexOutOfBoundsException
894 * If any of the following is true:
896 * <li> {@code srcBegin} is negative
897 * <li> {@code srcBegin} is greater than {@code srcEnd}
898 * <li> {@code srcEnd} is greater than the length of this String
899 * <li> {@code dstBegin} is negative
900 * <li> {@code dstBegin+(srcEnd-srcBegin)} is larger than {@code
905 public void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin) {
907 throw new StringIndexOutOfBoundsException(srcBegin);
909 if (srcEnd > count) {
910 throw new StringIndexOutOfBoundsException(srcEnd);
912 if (srcBegin > srcEnd) {
913 throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
916 int n = offset + srcEnd;
917 int i = offset + srcBegin;
918 char[] val = value; /* avoid getfield opcode */
921 dst[j++] = (byte)val[i++];
926 * Encodes this {@code String} into a sequence of bytes using the named
927 * charset, storing the result into a new byte array.
929 * <p> The behavior of this method when this string cannot be encoded in
930 * the given charset is unspecified. The {@link
931 * java.nio.charset.CharsetEncoder} class should be used when more control
932 * over the encoding process is required.
935 * The name of a supported {@linkplain java.nio.charset.Charset
938 * @return The resultant byte array
940 * @throws UnsupportedEncodingException
941 * If the named charset is not supported
945 public byte[] getBytes(String charsetName)
946 throws UnsupportedEncodingException
948 if (charsetName == null) throw new NullPointerException();
949 return StringCoding.encode(charsetName, value, offset, count);
953 * Encodes this {@code String} into a sequence of bytes using the given
954 * {@linkplain java.nio.charset.Charset charset}, storing the result into a
957 * <p> This method always replaces malformed-input and unmappable-character
958 * sequences with this charset's default replacement byte array. The
959 * {@link java.nio.charset.CharsetEncoder} class should be used when more
960 * control over the encoding process is required.
963 * The {@linkplain java.nio.charset.Charset} to be used to encode
966 * @return The resultant byte array
970 /* don't want dep on Charset
971 public byte[] getBytes(Charset charset) {
972 if (charset == null) throw new NullPointerException();
973 return StringCoding.encode(charset, value, offset, count);
978 * Encodes this {@code String} into a sequence of bytes using the
979 * platform's default charset, storing the result into a new byte array.
981 * <p> The behavior of this method when this string cannot be encoded in
982 * the default charset is unspecified. The {@link
983 * java.nio.charset.CharsetEncoder} class should be used when more control
984 * over the encoding process is required.
986 * @return The resultant byte array
990 public byte[] getBytes() {
991 return StringCoding.encode(value, offset, count);
995 * Compares this string to the specified object. The result is {@code
996 * true} if and only if the argument is not {@code null} and is a {@code
997 * String} object that represents the same sequence of characters as this
1001 * The object to compare this {@code String} against
1003 * @return {@code true} if the given object represents a {@code String}
1004 * equivalent to this string, {@code false} otherwise
1006 * @see #compareTo(String)
1007 * @see #equalsIgnoreCase(String)
1009 public boolean equals(Object anObject) {
1010 if (this == anObject) {
1013 if (anObject instanceof String) {
1014 String anotherString = (String)anObject;
1016 if (n == anotherString.count) {
1018 char v2[] = anotherString.value;
1020 int j = anotherString.offset;
1022 if (v1[i++] != v2[j++])
1032 * Compares this string to the specified {@code StringBuffer}. The result
1033 * is {@code true} if and only if this {@code String} represents the same
1034 * sequence of characters as the specified {@code StringBuffer}.
1037 * The {@code StringBuffer} to compare this {@code String} against
1039 * @return {@code true} if this {@code String} represents the same
1040 * sequence of characters as the specified {@code StringBuffer},
1041 * {@code false} otherwise
1045 public boolean contentEquals(StringBuffer sb) {
1047 return contentEquals((CharSequence)sb);
1052 * Compares this string to the specified {@code CharSequence}. The result
1053 * is {@code true} if and only if this {@code String} represents the same
1054 * sequence of char values as the specified sequence.
1057 * The sequence to compare this {@code String} against
1059 * @return {@code true} if this {@code String} represents the same
1060 * sequence of char values as the specified sequence, {@code
1065 public boolean contentEquals(CharSequence cs) {
1066 if (count != cs.length())
1068 // Argument is a StringBuffer, StringBuilder
1069 if (cs instanceof AbstractStringBuilder) {
1071 char v2[] = ((AbstractStringBuilder)cs).getValue();
1076 if (v1[i++] != v2[j++])
1081 // Argument is a String
1082 if (cs.equals(this))
1084 // Argument is a generic CharSequence
1090 if (v1[i++] != cs.charAt(j++))
1097 * Compares this {@code String} to another {@code String}, ignoring case
1098 * considerations. Two strings are considered equal ignoring case if they
1099 * are of the same length and corresponding characters in the two strings
1100 * are equal ignoring case.
1102 * <p> Two characters {@code c1} and {@code c2} are considered the same
1103 * ignoring case if at least one of the following is true:
1105 * <li> The two characters are the same (as compared by the
1106 * {@code ==} operator)
1107 * <li> Applying the method {@link
1108 * java.lang.Character#toUpperCase(char)} to each character
1109 * produces the same result
1110 * <li> Applying the method {@link
1111 * java.lang.Character#toLowerCase(char)} to each character
1112 * produces the same result
1115 * @param anotherString
1116 * The {@code String} to compare this {@code String} against
1118 * @return {@code true} if the argument is not {@code null} and it
1119 * represents an equivalent {@code String} ignoring case; {@code
1122 * @see #equals(Object)
1124 public boolean equalsIgnoreCase(String anotherString) {
1125 return (this == anotherString) ? true :
1126 (anotherString != null) && (anotherString.count == count) &&
1127 regionMatches(true, 0, anotherString, 0, count);
1131 * Compares two strings lexicographically.
1132 * The comparison is based on the Unicode value of each character in
1133 * the strings. The character sequence represented by this
1134 * <code>String</code> object is compared lexicographically to the
1135 * character sequence represented by the argument string. The result is
1136 * a negative integer if this <code>String</code> object
1137 * lexicographically precedes the argument string. The result is a
1138 * positive integer if this <code>String</code> object lexicographically
1139 * follows the argument string. The result is zero if the strings
1140 * are equal; <code>compareTo</code> returns <code>0</code> exactly when
1141 * the {@link #equals(Object)} method would return <code>true</code>.
1143 * This is the definition of lexicographic ordering. If two strings are
1144 * different, then either they have different characters at some index
1145 * that is a valid index for both strings, or their lengths are different,
1146 * or both. If they have different characters at one or more index
1147 * positions, let <i>k</i> be the smallest such index; then the string
1148 * whose character at position <i>k</i> has the smaller value, as
1149 * determined by using the < operator, lexicographically precedes the
1150 * other string. In this case, <code>compareTo</code> returns the
1151 * difference of the two character values at position <code>k</code> in
1152 * the two string -- that is, the value:
1154 * this.charAt(k)-anotherString.charAt(k)
1155 * </pre></blockquote>
1156 * If there is no index position at which they differ, then the shorter
1157 * string lexicographically precedes the longer string. In this case,
1158 * <code>compareTo</code> returns the difference of the lengths of the
1159 * strings -- that is, the value:
1161 * this.length()-anotherString.length()
1162 * </pre></blockquote>
1164 * @param anotherString the <code>String</code> to be compared.
1165 * @return the value <code>0</code> if the argument string is equal to
1166 * this string; a value less than <code>0</code> if this string
1167 * is lexicographically less than the string argument; and a
1168 * value greater than <code>0</code> if this string is
1169 * lexicographically greater than the string argument.
1171 public int compareTo(String anotherString) {
1173 int len2 = anotherString.count;
1174 int n = Math.min(len1, len2);
1176 char v2[] = anotherString.value;
1178 int j = anotherString.offset;
1204 * A Comparator that orders <code>String</code> objects as by
1205 * <code>compareToIgnoreCase</code>. This comparator is serializable.
1207 * Note that this Comparator does <em>not</em> take locale into account,
1208 * and will result in an unsatisfactory ordering for certain locales.
1209 * The java.text package provides <em>Collators</em> to allow
1210 * locale-sensitive ordering.
1212 * @see java.text.Collator#compare(String, String)
1215 public static final Comparator<String> CASE_INSENSITIVE_ORDER
1216 = new CaseInsensitiveComparator();
1217 private static class CaseInsensitiveComparator
1218 implements Comparator<String>, java.io.Serializable {
1219 // use serialVersionUID from JDK 1.2.2 for interoperability
1220 private static final long serialVersionUID = 8575799808933029326L;
1222 public int compare(String s1, String s2) {
1223 int n1 = s1.length();
1224 int n2 = s2.length();
1225 int min = Math.min(n1, n2);
1226 for (int i = 0; i < min; i++) {
1227 char c1 = s1.charAt(i);
1228 char c2 = s2.charAt(i);
1230 c1 = Character.toUpperCase(c1);
1231 c2 = Character.toUpperCase(c2);
1233 c1 = Character.toLowerCase(c1);
1234 c2 = Character.toLowerCase(c2);
1236 // No overflow because of numeric promotion
1247 * Compares two strings lexicographically, ignoring case
1248 * differences. This method returns an integer whose sign is that of
1249 * calling <code>compareTo</code> with normalized versions of the strings
1250 * where case differences have been eliminated by calling
1251 * <code>Character.toLowerCase(Character.toUpperCase(character))</code> on
1254 * Note that this method does <em>not</em> take locale into account,
1255 * and will result in an unsatisfactory ordering for certain locales.
1256 * The java.text package provides <em>collators</em> to allow
1257 * locale-sensitive ordering.
1259 * @param str the <code>String</code> to be compared.
1260 * @return a negative integer, zero, or a positive integer as the
1261 * specified String is greater than, equal to, or less
1262 * than this String, ignoring case considerations.
1263 * @see java.text.Collator#compare(String, String)
1266 public int compareToIgnoreCase(String str) {
1267 return CASE_INSENSITIVE_ORDER.compare(this, str);
1271 * Tests if two string regions are equal.
1273 * A substring of this <tt>String</tt> object is compared to a substring
1274 * of the argument other. The result is true if these substrings
1275 * represent identical character sequences. The substring of this
1276 * <tt>String</tt> object to be compared begins at index <tt>toffset</tt>
1277 * and has length <tt>len</tt>. The substring of other to be compared
1278 * begins at index <tt>ooffset</tt> and has length <tt>len</tt>. The
1279 * result is <tt>false</tt> if and only if at least one of the following
1281 * <ul><li><tt>toffset</tt> is negative.
1282 * <li><tt>ooffset</tt> is negative.
1283 * <li><tt>toffset+len</tt> is greater than the length of this
1284 * <tt>String</tt> object.
1285 * <li><tt>ooffset+len</tt> is greater than the length of the other
1287 * <li>There is some nonnegative integer <i>k</i> less than <tt>len</tt>
1289 * <tt>this.charAt(toffset+<i>k</i>) != other.charAt(ooffset+<i>k</i>)</tt>
1292 * @param toffset the starting offset of the subregion in this string.
1293 * @param other the string argument.
1294 * @param ooffset the starting offset of the subregion in the string
1296 * @param len the number of characters to compare.
1297 * @return <code>true</code> if the specified subregion of this string
1298 * exactly matches the specified subregion of the string argument;
1299 * <code>false</code> otherwise.
1301 public boolean regionMatches(int toffset, String other, int ooffset,
1304 int to = offset + toffset;
1305 char pa[] = other.value;
1306 int po = other.offset + ooffset;
1307 // Note: toffset, ooffset, or len might be near -1>>>1.
1308 if ((ooffset < 0) || (toffset < 0) || (toffset > (long)count - len)
1309 || (ooffset > (long)other.count - len)) {
1313 if (ta[to++] != pa[po++]) {
1321 * Tests if two string regions are equal.
1323 * A substring of this <tt>String</tt> object is compared to a substring
1324 * of the argument <tt>other</tt>. The result is <tt>true</tt> if these
1325 * substrings represent character sequences that are the same, ignoring
1326 * case if and only if <tt>ignoreCase</tt> is true. The substring of
1327 * this <tt>String</tt> object to be compared begins at index
1328 * <tt>toffset</tt> and has length <tt>len</tt>. The substring of
1329 * <tt>other</tt> to be compared begins at index <tt>ooffset</tt> and
1330 * has length <tt>len</tt>. The result is <tt>false</tt> if and only if
1331 * at least one of the following is true:
1332 * <ul><li><tt>toffset</tt> is negative.
1333 * <li><tt>ooffset</tt> is negative.
1334 * <li><tt>toffset+len</tt> is greater than the length of this
1335 * <tt>String</tt> object.
1336 * <li><tt>ooffset+len</tt> is greater than the length of the other
1338 * <li><tt>ignoreCase</tt> is <tt>false</tt> and there is some nonnegative
1339 * integer <i>k</i> less than <tt>len</tt> such that:
1341 * this.charAt(toffset+k) != other.charAt(ooffset+k)
1342 * </pre></blockquote>
1343 * <li><tt>ignoreCase</tt> is <tt>true</tt> and there is some nonnegative
1344 * integer <i>k</i> less than <tt>len</tt> such that:
1346 * Character.toLowerCase(this.charAt(toffset+k)) !=
1347 Character.toLowerCase(other.charAt(ooffset+k))
1348 * </pre></blockquote>
1351 * Character.toUpperCase(this.charAt(toffset+k)) !=
1352 * Character.toUpperCase(other.charAt(ooffset+k))
1353 * </pre></blockquote>
1356 * @param ignoreCase if <code>true</code>, ignore case when comparing
1358 * @param toffset the starting offset of the subregion in this
1360 * @param other the string argument.
1361 * @param ooffset the starting offset of the subregion in the string
1363 * @param len the number of characters to compare.
1364 * @return <code>true</code> if the specified subregion of this string
1365 * matches the specified subregion of the string argument;
1366 * <code>false</code> otherwise. Whether the matching is exact
1367 * or case insensitive depends on the <code>ignoreCase</code>
1370 public boolean regionMatches(boolean ignoreCase, int toffset,
1371 String other, int ooffset, int len) {
1373 int to = offset + toffset;
1374 char pa[] = other.value;
1375 int po = other.offset + ooffset;
1376 // Note: toffset, ooffset, or len might be near -1>>>1.
1377 if ((ooffset < 0) || (toffset < 0) || (toffset > (long)count - len) ||
1378 (ooffset > (long)other.count - len)) {
1388 // If characters don't match but case may be ignored,
1389 // try converting both characters to uppercase.
1390 // If the results match, then the comparison scan should
1392 char u1 = Character.toUpperCase(c1);
1393 char u2 = Character.toUpperCase(c2);
1397 // Unfortunately, conversion to uppercase does not work properly
1398 // for the Georgian alphabet, which has strange rules about case
1399 // conversion. So we need to make one last check before
1401 if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) {
1411 * Tests if the substring of this string beginning at the
1412 * specified index starts with the specified prefix.
1414 * @param prefix the prefix.
1415 * @param toffset where to begin looking in this string.
1416 * @return <code>true</code> if the character sequence represented by the
1417 * argument is a prefix of the substring of this object starting
1418 * at index <code>toffset</code>; <code>false</code> otherwise.
1419 * The result is <code>false</code> if <code>toffset</code> is
1420 * negative or greater than the length of this
1421 * <code>String</code> object; otherwise the result is the same
1422 * as the result of the expression
1424 * this.substring(toffset).startsWith(prefix)
1427 public boolean startsWith(String prefix, int toffset) {
1429 int to = offset + toffset;
1430 char pa[] = prefix.value;
1431 int po = prefix.offset;
1432 int pc = prefix.count;
1433 // Note: toffset might be near -1>>>1.
1434 if ((toffset < 0) || (toffset > count - pc)) {
1438 if (ta[to++] != pa[po++]) {
1446 * Tests if this string starts with the specified prefix.
1448 * @param prefix the prefix.
1449 * @return <code>true</code> if the character sequence represented by the
1450 * argument is a prefix of the character sequence represented by
1451 * this string; <code>false</code> otherwise.
1452 * Note also that <code>true</code> will be returned if the
1453 * argument is an empty string or is equal to this
1454 * <code>String</code> object as determined by the
1455 * {@link #equals(Object)} method.
1458 public boolean startsWith(String prefix) {
1459 return startsWith(prefix, 0);
1463 * Tests if this string ends with the specified suffix.
1465 * @param suffix the suffix.
1466 * @return <code>true</code> if the character sequence represented by the
1467 * argument is a suffix of the character sequence represented by
1468 * this object; <code>false</code> otherwise. Note that the
1469 * result will be <code>true</code> if the argument is the
1470 * empty string or is equal to this <code>String</code> object
1471 * as determined by the {@link #equals(Object)} method.
1473 public boolean endsWith(String suffix) {
1474 return startsWith(suffix, count - suffix.count);
1478 * Returns a hash code for this string. The hash code for a
1479 * <code>String</code> object is computed as
1481 * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
1482 * </pre></blockquote>
1483 * using <code>int</code> arithmetic, where <code>s[i]</code> is the
1484 * <i>i</i>th character of the string, <code>n</code> is the length of
1485 * the string, and <code>^</code> indicates exponentiation.
1486 * (The hash value of the empty string is zero.)
1488 * @return a hash code value for this object.
1490 public int hashCode() {
1492 if (h == 0 && count > 0) {
1497 for (int i = 0; i < len; i++) {
1498 h = 31*h + val[off++];
1506 * Returns the index within this string of the first occurrence of
1507 * the specified character. If a character with value
1508 * <code>ch</code> occurs in the character sequence represented by
1509 * this <code>String</code> object, then the index (in Unicode
1510 * code units) of the first such occurrence is returned. For
1511 * values of <code>ch</code> in the range from 0 to 0xFFFF
1512 * (inclusive), this is the smallest value <i>k</i> such that:
1514 * this.charAt(<i>k</i>) == ch
1515 * </pre></blockquote>
1516 * is true. For other values of <code>ch</code>, it is the
1517 * smallest value <i>k</i> such that:
1519 * this.codePointAt(<i>k</i>) == ch
1520 * </pre></blockquote>
1521 * is true. In either case, if no such character occurs in this
1522 * string, then <code>-1</code> is returned.
1524 * @param ch a character (Unicode code point).
1525 * @return the index of the first occurrence of the character in the
1526 * character sequence represented by this object, or
1527 * <code>-1</code> if the character does not occur.
1529 public int indexOf(int ch) {
1530 return indexOf(ch, 0);
1534 * Returns the index within this string of the first occurrence of the
1535 * specified character, starting the search at the specified index.
1537 * If a character with value <code>ch</code> occurs in the
1538 * character sequence represented by this <code>String</code>
1539 * object at an index no smaller than <code>fromIndex</code>, then
1540 * the index of the first such occurrence is returned. For values
1541 * of <code>ch</code> in the range from 0 to 0xFFFF (inclusive),
1542 * this is the smallest value <i>k</i> such that:
1544 * (this.charAt(<i>k</i>) == ch) && (<i>k</i> >= fromIndex)
1545 * </pre></blockquote>
1546 * is true. For other values of <code>ch</code>, it is the
1547 * smallest value <i>k</i> such that:
1549 * (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> >= fromIndex)
1550 * </pre></blockquote>
1551 * is true. In either case, if no such character occurs in this
1552 * string at or after position <code>fromIndex</code>, then
1553 * <code>-1</code> is returned.
1556 * There is no restriction on the value of <code>fromIndex</code>. If it
1557 * is negative, it has the same effect as if it were zero: this entire
1558 * string may be searched. If it is greater than the length of this
1559 * string, it has the same effect as if it were equal to the length of
1560 * this string: <code>-1</code> is returned.
1562 * <p>All indices are specified in <code>char</code> values
1563 * (Unicode code units).
1565 * @param ch a character (Unicode code point).
1566 * @param fromIndex the index to start the search from.
1567 * @return the index of the first occurrence of the character in the
1568 * character sequence represented by this object that is greater
1569 * than or equal to <code>fromIndex</code>, or <code>-1</code>
1570 * if the character does not occur.
1572 public int indexOf(int ch, int fromIndex) {
1573 if (fromIndex < 0) {
1575 } else if (fromIndex >= count) {
1576 // Note: fromIndex might be near -1>>>1.
1580 if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
1581 // handle most cases here (ch is a BMP code point or a
1582 // negative value (invalid code point))
1583 final char[] value = this.value;
1584 final int offset = this.offset;
1585 final int max = offset + count;
1586 for (int i = offset + fromIndex; i < max ; i++) {
1587 if (value[i] == ch) {
1593 return indexOfSupplementary(ch, fromIndex);
1598 * Handles (rare) calls of indexOf with a supplementary character.
1600 private int indexOfSupplementary(int ch, int fromIndex) {
1601 if (Character.isValidCodePoint(ch)) {
1602 final char[] value = this.value;
1603 final int offset = this.offset;
1604 final char hi = Character.highSurrogate(ch);
1605 final char lo = Character.lowSurrogate(ch);
1606 final int max = offset + count - 1;
1607 for (int i = offset + fromIndex; i < max; i++) {
1608 if (value[i] == hi && value[i+1] == lo) {
1617 * Returns the index within this string of the last occurrence of
1618 * the specified character. For values of <code>ch</code> in the
1619 * range from 0 to 0xFFFF (inclusive), the index (in Unicode code
1620 * units) returned is the largest value <i>k</i> such that:
1622 * this.charAt(<i>k</i>) == ch
1623 * </pre></blockquote>
1624 * is true. For other values of <code>ch</code>, it is the
1625 * largest value <i>k</i> such that:
1627 * this.codePointAt(<i>k</i>) == ch
1628 * </pre></blockquote>
1629 * is true. In either case, if no such character occurs in this
1630 * string, then <code>-1</code> is returned. The
1631 * <code>String</code> is searched backwards starting at the last
1634 * @param ch a character (Unicode code point).
1635 * @return the index of the last occurrence of the character in the
1636 * character sequence represented by this object, or
1637 * <code>-1</code> if the character does not occur.
1639 public int lastIndexOf(int ch) {
1640 return lastIndexOf(ch, count - 1);
1644 * Returns the index within this string of the last occurrence of
1645 * the specified character, searching backward starting at the
1646 * specified index. For values of <code>ch</code> in the range
1647 * from 0 to 0xFFFF (inclusive), the index returned is the largest
1648 * value <i>k</i> such that:
1650 * (this.charAt(<i>k</i>) == ch) && (<i>k</i> <= fromIndex)
1651 * </pre></blockquote>
1652 * is true. For other values of <code>ch</code>, it is the
1653 * largest value <i>k</i> such that:
1655 * (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> <= fromIndex)
1656 * </pre></blockquote>
1657 * is true. In either case, if no such character occurs in this
1658 * string at or before position <code>fromIndex</code>, then
1659 * <code>-1</code> is returned.
1661 * <p>All indices are specified in <code>char</code> values
1662 * (Unicode code units).
1664 * @param ch a character (Unicode code point).
1665 * @param fromIndex the index to start the search from. There is no
1666 * restriction on the value of <code>fromIndex</code>. If it is
1667 * greater than or equal to the length of this string, it has
1668 * the same effect as if it were equal to one less than the
1669 * length of this string: this entire string may be searched.
1670 * If it is negative, it has the same effect as if it were -1:
1672 * @return the index of the last occurrence of the character in the
1673 * character sequence represented by this object that is less
1674 * than or equal to <code>fromIndex</code>, or <code>-1</code>
1675 * if the character does not occur before that point.
1677 public int lastIndexOf(int ch, int fromIndex) {
1678 if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
1679 // handle most cases here (ch is a BMP code point or a
1680 // negative value (invalid code point))
1681 final char[] value = this.value;
1682 final int offset = this.offset;
1683 int i = offset + Math.min(fromIndex, count - 1);
1684 for (; i >= offset ; i--) {
1685 if (value[i] == ch) {
1691 return lastIndexOfSupplementary(ch, fromIndex);
1696 * Handles (rare) calls of lastIndexOf with a supplementary character.
1698 private int lastIndexOfSupplementary(int ch, int fromIndex) {
1699 if (Character.isValidCodePoint(ch)) {
1700 final char[] value = this.value;
1701 final int offset = this.offset;
1702 char hi = Character.highSurrogate(ch);
1703 char lo = Character.lowSurrogate(ch);
1704 int i = offset + Math.min(fromIndex, count - 2);
1705 for (; i >= offset; i--) {
1706 if (value[i] == hi && value[i+1] == lo) {
1715 * Returns the index within this string of the first occurrence of the
1716 * specified substring.
1718 * <p>The returned index is the smallest value <i>k</i> for which:
1720 * this.startsWith(str, <i>k</i>)
1721 * </pre></blockquote>
1722 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1724 * @param str the substring to search for.
1725 * @return the index of the first occurrence of the specified substring,
1726 * or {@code -1} if there is no such occurrence.
1728 public int indexOf(String str) {
1729 return indexOf(str, 0);
1733 * Returns the index within this string of the first occurrence of the
1734 * specified substring, starting at the specified index.
1736 * <p>The returned index is the smallest value <i>k</i> for which:
1738 * <i>k</i> >= fromIndex && this.startsWith(str, <i>k</i>)
1739 * </pre></blockquote>
1740 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1742 * @param str the substring to search for.
1743 * @param fromIndex the index from which to start the search.
1744 * @return the index of the first occurrence of the specified substring,
1745 * starting at the specified index,
1746 * or {@code -1} if there is no such occurrence.
1748 public int indexOf(String str, int fromIndex) {
1749 return indexOf(value, offset, count,
1750 str.value, str.offset, str.count, fromIndex);
1754 * Code shared by String and StringBuffer to do searches. The
1755 * source is the character array being searched, and the target
1756 * is the string being searched for.
1758 * @param source the characters being searched.
1759 * @param sourceOffset offset of the source string.
1760 * @param sourceCount count of the source string.
1761 * @param target the characters being searched for.
1762 * @param targetOffset offset of the target string.
1763 * @param targetCount count of the target string.
1764 * @param fromIndex the index to begin searching from.
1766 static int indexOf(char[] source, int sourceOffset, int sourceCount,
1767 char[] target, int targetOffset, int targetCount,
1769 if (fromIndex >= sourceCount) {
1770 return (targetCount == 0 ? sourceCount : -1);
1772 if (fromIndex < 0) {
1775 if (targetCount == 0) {
1779 char first = target[targetOffset];
1780 int max = sourceOffset + (sourceCount - targetCount);
1782 for (int i = sourceOffset + fromIndex; i <= max; i++) {
1783 /* Look for first character. */
1784 if (source[i] != first) {
1785 while (++i <= max && source[i] != first);
1788 /* Found first character, now look at the rest of v2 */
1791 int end = j + targetCount - 1;
1792 for (int k = targetOffset + 1; j < end && source[j] ==
1793 target[k]; j++, k++);
1796 /* Found whole string. */
1797 return i - sourceOffset;
1805 * Returns the index within this string of the last occurrence of the
1806 * specified substring. The last occurrence of the empty string ""
1807 * is considered to occur at the index value {@code this.length()}.
1809 * <p>The returned index is the largest value <i>k</i> for which:
1811 * this.startsWith(str, <i>k</i>)
1812 * </pre></blockquote>
1813 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1815 * @param str the substring to search for.
1816 * @return the index of the last occurrence of the specified substring,
1817 * or {@code -1} if there is no such occurrence.
1819 public int lastIndexOf(String str) {
1820 return lastIndexOf(str, count);
1824 * Returns the index within this string of the last occurrence of the
1825 * specified substring, searching backward starting at the specified index.
1827 * <p>The returned index is the largest value <i>k</i> for which:
1829 * <i>k</i> <= fromIndex && this.startsWith(str, <i>k</i>)
1830 * </pre></blockquote>
1831 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1833 * @param str the substring to search for.
1834 * @param fromIndex the index to start the search from.
1835 * @return the index of the last occurrence of the specified substring,
1836 * searching backward from the specified index,
1837 * or {@code -1} if there is no such occurrence.
1839 public int lastIndexOf(String str, int fromIndex) {
1840 return lastIndexOf(value, offset, count,
1841 str.value, str.offset, str.count, fromIndex);
1845 * Code shared by String and StringBuffer to do searches. The
1846 * source is the character array being searched, and the target
1847 * is the string being searched for.
1849 * @param source the characters being searched.
1850 * @param sourceOffset offset of the source string.
1851 * @param sourceCount count of the source string.
1852 * @param target the characters being searched for.
1853 * @param targetOffset offset of the target string.
1854 * @param targetCount count of the target string.
1855 * @param fromIndex the index to begin searching from.
1857 static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
1858 char[] target, int targetOffset, int targetCount,
1861 * Check arguments; return immediately where possible. For
1862 * consistency, don't check for null str.
1864 int rightIndex = sourceCount - targetCount;
1865 if (fromIndex < 0) {
1868 if (fromIndex > rightIndex) {
1869 fromIndex = rightIndex;
1871 /* Empty string always matches. */
1872 if (targetCount == 0) {
1876 int strLastIndex = targetOffset + targetCount - 1;
1877 char strLastChar = target[strLastIndex];
1878 int min = sourceOffset + targetCount - 1;
1879 int i = min + fromIndex;
1881 startSearchForLastChar:
1883 while (i >= min && source[i] != strLastChar) {
1890 int start = j - (targetCount - 1);
1891 int k = strLastIndex - 1;
1894 if (source[j--] != target[k--]) {
1896 continue startSearchForLastChar;
1899 return start - sourceOffset + 1;
1904 * Returns a new string that is a substring of this string. The
1905 * substring begins with the character at the specified index and
1906 * extends to the end of this string. <p>
1909 * "unhappy".substring(2) returns "happy"
1910 * "Harbison".substring(3) returns "bison"
1911 * "emptiness".substring(9) returns "" (an empty string)
1912 * </pre></blockquote>
1914 * @param beginIndex the beginning index, inclusive.
1915 * @return the specified substring.
1916 * @exception IndexOutOfBoundsException if
1917 * <code>beginIndex</code> is negative or larger than the
1918 * length of this <code>String</code> object.
1920 public String substring(int beginIndex) {
1921 return substring(beginIndex, count);
1925 * Returns a new string that is a substring of this string. The
1926 * substring begins at the specified <code>beginIndex</code> and
1927 * extends to the character at index <code>endIndex - 1</code>.
1928 * Thus the length of the substring is <code>endIndex-beginIndex</code>.
1932 * "hamburger".substring(4, 8) returns "urge"
1933 * "smiles".substring(1, 5) returns "mile"
1934 * </pre></blockquote>
1936 * @param beginIndex the beginning index, inclusive.
1937 * @param endIndex the ending index, exclusive.
1938 * @return the specified substring.
1939 * @exception IndexOutOfBoundsException if the
1940 * <code>beginIndex</code> is negative, or
1941 * <code>endIndex</code> is larger than the length of
1942 * this <code>String</code> object, or
1943 * <code>beginIndex</code> is larger than
1944 * <code>endIndex</code>.
1946 public String substring(int beginIndex, int endIndex) {
1947 if (beginIndex < 0) {
1948 throw new StringIndexOutOfBoundsException(beginIndex);
1950 if (endIndex > count) {
1951 throw new StringIndexOutOfBoundsException(endIndex);
1953 if (beginIndex > endIndex) {
1954 throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
1956 return ((beginIndex == 0) && (endIndex == count)) ? this :
1957 new String(offset + beginIndex, endIndex - beginIndex, value);
1961 * Returns a new character sequence that is a subsequence of this sequence.
1963 * <p> An invocation of this method of the form
1966 * str.subSequence(begin, end)</pre></blockquote>
1968 * behaves in exactly the same way as the invocation
1971 * str.substring(begin, end)</pre></blockquote>
1973 * This method is defined so that the <tt>String</tt> class can implement
1974 * the {@link CharSequence} interface. </p>
1976 * @param beginIndex the begin index, inclusive.
1977 * @param endIndex the end index, exclusive.
1978 * @return the specified subsequence.
1980 * @throws IndexOutOfBoundsException
1981 * if <tt>beginIndex</tt> or <tt>endIndex</tt> are negative,
1982 * if <tt>endIndex</tt> is greater than <tt>length()</tt>,
1983 * or if <tt>beginIndex</tt> is greater than <tt>startIndex</tt>
1988 public CharSequence subSequence(int beginIndex, int endIndex) {
1989 return this.substring(beginIndex, endIndex);
1993 * Concatenates the specified string to the end of this string.
1995 * If the length of the argument string is <code>0</code>, then this
1996 * <code>String</code> object is returned. Otherwise, a new
1997 * <code>String</code> object is created, representing a character
1998 * sequence that is the concatenation of the character sequence
1999 * represented by this <code>String</code> object and the character
2000 * sequence represented by the argument string.<p>
2003 * "cares".concat("s") returns "caress"
2004 * "to".concat("get").concat("her") returns "together"
2005 * </pre></blockquote>
2007 * @param str the <code>String</code> that is concatenated to the end
2008 * of this <code>String</code>.
2009 * @return a string that represents the concatenation of this object's
2010 * characters followed by the string argument's characters.
2012 public String concat(String str) {
2013 int otherLen = str.length();
2014 if (otherLen == 0) {
2017 char buf[] = new char[count + otherLen];
2018 getChars(0, count, buf, 0);
2019 str.getChars(0, otherLen, buf, count);
2020 return new String(0, count + otherLen, buf);
2024 * Returns a new string resulting from replacing all occurrences of
2025 * <code>oldChar</code> in this string with <code>newChar</code>.
2027 * If the character <code>oldChar</code> does not occur in the
2028 * character sequence represented by this <code>String</code> object,
2029 * then a reference to this <code>String</code> object is returned.
2030 * Otherwise, a new <code>String</code> object is created that
2031 * represents a character sequence identical to the character sequence
2032 * represented by this <code>String</code> object, except that every
2033 * occurrence of <code>oldChar</code> is replaced by an occurrence
2034 * of <code>newChar</code>.
2038 * "mesquite in your cellar".replace('e', 'o')
2039 * returns "mosquito in your collar"
2040 * "the war of baronets".replace('r', 'y')
2041 * returns "the way of bayonets"
2042 * "sparring with a purple porpoise".replace('p', 't')
2043 * returns "starring with a turtle tortoise"
2044 * "JonL".replace('q', 'x') returns "JonL" (no change)
2045 * </pre></blockquote>
2047 * @param oldChar the old character.
2048 * @param newChar the new character.
2049 * @return a string derived from this string by replacing every
2050 * occurrence of <code>oldChar</code> with <code>newChar</code>.
2052 public String replace(char oldChar, char newChar) {
2053 if (oldChar != newChar) {
2056 char[] val = value; /* avoid getfield opcode */
2057 int off = offset; /* avoid getfield opcode */
2060 if (val[off + i] == oldChar) {
2065 char buf[] = new char[len];
2066 for (int j = 0 ; j < i ; j++) {
2067 buf[j] = val[off+j];
2070 char c = val[off + i];
2071 buf[i] = (c == oldChar) ? newChar : c;
2074 return new String(0, len, buf);
2081 * Tells whether or not this string matches the given <a
2082 * href="../util/regex/Pattern.html#sum">regular expression</a>.
2084 * <p> An invocation of this method of the form
2085 * <i>str</i><tt>.matches(</tt><i>regex</i><tt>)</tt> yields exactly the
2086 * same result as the expression
2088 * <blockquote><tt> {@link java.util.regex.Pattern}.{@link
2089 * java.util.regex.Pattern#matches(String,CharSequence)
2090 * matches}(</tt><i>regex</i><tt>,</tt> <i>str</i><tt>)</tt></blockquote>
2093 * the regular expression to which this string is to be matched
2095 * @return <tt>true</tt> if, and only if, this string matches the
2096 * given regular expression
2098 * @throws PatternSyntaxException
2099 * if the regular expression's syntax is invalid
2101 * @see java.util.regex.Pattern
2106 public boolean matches(String regex) {
2107 throw new UnsupportedOperationException();
2111 * Returns true if and only if this string contains the specified
2112 * sequence of char values.
2114 * @param s the sequence to search for
2115 * @return true if this string contains <code>s</code>, false otherwise
2116 * @throws NullPointerException if <code>s</code> is <code>null</code>
2119 public boolean contains(CharSequence s) {
2120 return indexOf(s.toString()) > -1;
2124 * Replaces the first substring of this string that matches the given <a
2125 * href="../util/regex/Pattern.html#sum">regular expression</a> with the
2126 * given replacement.
2128 * <p> An invocation of this method of the form
2129 * <i>str</i><tt>.replaceFirst(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt>
2130 * yields exactly the same result as the expression
2133 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2134 * compile}(</tt><i>regex</i><tt>).{@link
2135 * java.util.regex.Pattern#matcher(java.lang.CharSequence)
2136 * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceFirst
2137 * replaceFirst}(</tt><i>repl</i><tt>)</tt></blockquote>
2140 * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the
2141 * replacement string may cause the results to be different than if it were
2142 * being treated as a literal replacement string; see
2143 * {@link java.util.regex.Matcher#replaceFirst}.
2144 * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
2145 * meaning of these characters, if desired.
2148 * the regular expression to which this string is to be matched
2149 * @param replacement
2150 * the string to be substituted for the first match
2152 * @return The resulting <tt>String</tt>
2154 * @throws PatternSyntaxException
2155 * if the regular expression's syntax is invalid
2157 * @see java.util.regex.Pattern
2162 public String replaceFirst(String regex, String replacement) {
2163 throw new UnsupportedOperationException();
2167 * Replaces each substring of this string that matches the given <a
2168 * href="../util/regex/Pattern.html#sum">regular expression</a> with the
2169 * given replacement.
2171 * <p> An invocation of this method of the form
2172 * <i>str</i><tt>.replaceAll(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt>
2173 * yields exactly the same result as the expression
2176 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2177 * compile}(</tt><i>regex</i><tt>).{@link
2178 * java.util.regex.Pattern#matcher(java.lang.CharSequence)
2179 * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceAll
2180 * replaceAll}(</tt><i>repl</i><tt>)</tt></blockquote>
2183 * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the
2184 * replacement string may cause the results to be different than if it were
2185 * being treated as a literal replacement string; see
2186 * {@link java.util.regex.Matcher#replaceAll Matcher.replaceAll}.
2187 * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
2188 * meaning of these characters, if desired.
2191 * the regular expression to which this string is to be matched
2192 * @param replacement
2193 * the string to be substituted for each match
2195 * @return The resulting <tt>String</tt>
2197 * @throws PatternSyntaxException
2198 * if the regular expression's syntax is invalid
2200 * @see java.util.regex.Pattern
2205 public String replaceAll(String regex, String replacement) {
2206 throw new UnsupportedOperationException();
2210 * Replaces each substring of this string that matches the literal target
2211 * sequence with the specified literal replacement sequence. The
2212 * replacement proceeds from the beginning of the string to the end, for
2213 * example, replacing "aa" with "b" in the string "aaa" will result in
2214 * "ba" rather than "ab".
2216 * @param target The sequence of char values to be replaced
2217 * @param replacement The replacement sequence of char values
2218 * @return The resulting string
2219 * @throws NullPointerException if <code>target</code> or
2220 * <code>replacement</code> is <code>null</code>.
2223 public String replace(CharSequence target, CharSequence replacement) {
2224 throw new UnsupportedOperationException("This one should be supported, but without dep on rest of regexp");
2228 * Splits this string around matches of the given
2229 * <a href="../util/regex/Pattern.html#sum">regular expression</a>.
2231 * <p> The array returned by this method contains each substring of this
2232 * string that is terminated by another substring that matches the given
2233 * expression or is terminated by the end of the string. The substrings in
2234 * the array are in the order in which they occur in this string. If the
2235 * expression does not match any part of the input then the resulting array
2236 * has just one element, namely this string.
2238 * <p> The <tt>limit</tt> parameter controls the number of times the
2239 * pattern is applied and therefore affects the length of the resulting
2240 * array. If the limit <i>n</i> is greater than zero then the pattern
2241 * will be applied at most <i>n</i> - 1 times, the array's
2242 * length will be no greater than <i>n</i>, and the array's last entry
2243 * will contain all input beyond the last matched delimiter. If <i>n</i>
2244 * is non-positive then the pattern will be applied as many times as
2245 * possible and the array can have any length. If <i>n</i> is zero then
2246 * the pattern will be applied as many times as possible, the array can
2247 * have any length, and trailing empty strings will be discarded.
2249 * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the
2250 * following results with these parameters:
2252 * <blockquote><table cellpadding=1 cellspacing=0 summary="Split example showing regex, limit, and result">
2258 * <tr><td align=center>:</td>
2259 * <td align=center>2</td>
2260 * <td><tt>{ "boo", "and:foo" }</tt></td></tr>
2261 * <tr><td align=center>:</td>
2262 * <td align=center>5</td>
2263 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2264 * <tr><td align=center>:</td>
2265 * <td align=center>-2</td>
2266 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2267 * <tr><td align=center>o</td>
2268 * <td align=center>5</td>
2269 * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
2270 * <tr><td align=center>o</td>
2271 * <td align=center>-2</td>
2272 * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
2273 * <tr><td align=center>o</td>
2274 * <td align=center>0</td>
2275 * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
2276 * </table></blockquote>
2278 * <p> An invocation of this method of the form
2279 * <i>str.</i><tt>split(</tt><i>regex</i><tt>,</tt> <i>n</i><tt>)</tt>
2280 * yields the same result as the expression
2283 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2284 * compile}<tt>(</tt><i>regex</i><tt>)</tt>.{@link
2285 * java.util.regex.Pattern#split(java.lang.CharSequence,int)
2286 * split}<tt>(</tt><i>str</i><tt>,</tt> <i>n</i><tt>)</tt>
2291 * the delimiting regular expression
2294 * the result threshold, as described above
2296 * @return the array of strings computed by splitting this string
2297 * around matches of the given regular expression
2299 * @throws PatternSyntaxException
2300 * if the regular expression's syntax is invalid
2302 * @see java.util.regex.Pattern
2307 public String[] split(String regex, int limit) {
2308 throw new UnsupportedOperationException("Needs regexp");
2312 * Splits this string around matches of the given <a
2313 * href="../util/regex/Pattern.html#sum">regular expression</a>.
2315 * <p> This method works as if by invoking the two-argument {@link
2316 * #split(String, int) split} method with the given expression and a limit
2317 * argument of zero. Trailing empty strings are therefore not included in
2318 * the resulting array.
2320 * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the following
2321 * results with these expressions:
2323 * <blockquote><table cellpadding=1 cellspacing=0 summary="Split examples showing regex and result">
2328 * <tr><td align=center>:</td>
2329 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2330 * <tr><td align=center>o</td>
2331 * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
2332 * </table></blockquote>
2336 * the delimiting regular expression
2338 * @return the array of strings computed by splitting this string
2339 * around matches of the given regular expression
2341 * @throws PatternSyntaxException
2342 * if the regular expression's syntax is invalid
2344 * @see java.util.regex.Pattern
2349 public String[] split(String regex) {
2350 return split(regex, 0);
2354 * Converts all of the characters in this <code>String</code> to lower
2355 * case using the rules of the given <code>Locale</code>. Case mapping is based
2356 * on the Unicode Standard version specified by the {@link java.lang.Character Character}
2357 * class. Since case mappings are not always 1:1 char mappings, the resulting
2358 * <code>String</code> may be a different length than the original <code>String</code>.
2360 * Examples of lowercase mappings are in the following table:
2361 * <table border="1" summary="Lowercase mapping examples showing language code of locale, upper case, lower case, and description">
2363 * <th>Language Code of Locale</th>
2364 * <th>Upper Case</th>
2365 * <th>Lower Case</th>
2366 * <th>Description</th>
2369 * <td>tr (Turkish)</td>
2370 * <td>\u0130</td>
2371 * <td>\u0069</td>
2372 * <td>capital letter I with dot above -> small letter i</td>
2375 * <td>tr (Turkish)</td>
2376 * <td>\u0049</td>
2377 * <td>\u0131</td>
2378 * <td>capital letter I -> small letter dotless i </td>
2382 * <td>French Fries</td>
2383 * <td>french fries</td>
2384 * <td>lowercased all chars in String</td>
2388 * <td><img src="doc-files/capiota.gif" alt="capiota"><img src="doc-files/capchi.gif" alt="capchi">
2389 * <img src="doc-files/captheta.gif" alt="captheta"><img src="doc-files/capupsil.gif" alt="capupsil">
2390 * <img src="doc-files/capsigma.gif" alt="capsigma"></td>
2391 * <td><img src="doc-files/iota.gif" alt="iota"><img src="doc-files/chi.gif" alt="chi">
2392 * <img src="doc-files/theta.gif" alt="theta"><img src="doc-files/upsilon.gif" alt="upsilon">
2393 * <img src="doc-files/sigma1.gif" alt="sigma"></td>
2394 * <td>lowercased all chars in String</td>
2398 * @param locale use the case transformation rules for this locale
2399 * @return the <code>String</code>, converted to lowercase.
2400 * @see java.lang.String#toLowerCase()
2401 * @see java.lang.String#toUpperCase()
2402 * @see java.lang.String#toUpperCase(Locale)
2405 // public String toLowerCase(Locale locale) {
2406 // if (locale == null) {
2407 // throw new NullPointerException();
2412 // /* Now check if there are any characters that need to be changed. */
2414 // for (firstUpper = 0 ; firstUpper < count; ) {
2415 // char c = value[offset+firstUpper];
2416 // if ((c >= Character.MIN_HIGH_SURROGATE) &&
2417 // (c <= Character.MAX_HIGH_SURROGATE)) {
2418 // int supplChar = codePointAt(firstUpper);
2419 // if (supplChar != Character.toLowerCase(supplChar)) {
2422 // firstUpper += Character.charCount(supplChar);
2424 // if (c != Character.toLowerCase(c)) {
2433 // char[] result = new char[count];
2434 // int resultOffset = 0; /* result may grow, so i+resultOffset
2435 // * is the write location in result */
2437 // /* Just copy the first few lowerCase characters. */
2438 // System.arraycopy(value, offset, result, 0, firstUpper);
2440 // String lang = locale.getLanguage();
2441 // boolean localeDependent =
2442 // (lang == "tr" || lang == "az" || lang == "lt");
2443 // char[] lowerCharArray;
2447 // for (int i = firstUpper; i < count; i += srcCount) {
2448 // srcChar = (int)value[offset+i];
2449 // if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
2450 // (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
2451 // srcChar = codePointAt(i);
2452 // srcCount = Character.charCount(srcChar);
2456 // if (localeDependent || srcChar == '\u03A3') { // GREEK CAPITAL LETTER SIGMA
2457 // lowerChar = ConditionalSpecialCasing.toLowerCaseEx(this, i, locale);
2458 // } else if (srcChar == '\u0130') { // LATIN CAPITAL LETTER I DOT
2459 // lowerChar = Character.ERROR;
2461 // lowerChar = Character.toLowerCase(srcChar);
2463 // if ((lowerChar == Character.ERROR) ||
2464 // (lowerChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
2465 // if (lowerChar == Character.ERROR) {
2466 // if (!localeDependent && srcChar == '\u0130') {
2468 // ConditionalSpecialCasing.toLowerCaseCharArray(this, i, Locale.ENGLISH);
2471 // ConditionalSpecialCasing.toLowerCaseCharArray(this, i, locale);
2473 // } else if (srcCount == 2) {
2474 // resultOffset += Character.toChars(lowerChar, result, i + resultOffset) - srcCount;
2477 // lowerCharArray = Character.toChars(lowerChar);
2480 // /* Grow result if needed */
2481 // int mapLen = lowerCharArray.length;
2482 // if (mapLen > srcCount) {
2483 // char[] result2 = new char[result.length + mapLen - srcCount];
2484 // System.arraycopy(result, 0, result2, 0,
2485 // i + resultOffset);
2486 // result = result2;
2488 // for (int x=0; x<mapLen; ++x) {
2489 // result[i+resultOffset+x] = lowerCharArray[x];
2491 // resultOffset += (mapLen - srcCount);
2493 // result[i+resultOffset] = (char)lowerChar;
2496 // return new String(0, count+resultOffset, result);
2500 * Converts all of the characters in this <code>String</code> to lower
2501 * case using the rules of the default locale. This is equivalent to calling
2502 * <code>toLowerCase(Locale.getDefault())</code>.
2504 * <b>Note:</b> This method is locale sensitive, and may produce unexpected
2505 * results if used for strings that are intended to be interpreted locale
2507 * Examples are programming language identifiers, protocol keys, and HTML
2509 * For instance, <code>"TITLE".toLowerCase()</code> in a Turkish locale
2510 * returns <code>"t\u005Cu0131tle"</code>, where '\u005Cu0131' is the
2511 * LATIN SMALL LETTER DOTLESS I character.
2512 * To obtain correct results for locale insensitive strings, use
2513 * <code>toLowerCase(Locale.ENGLISH)</code>.
2515 * @return the <code>String</code>, converted to lowercase.
2516 * @see java.lang.String#toLowerCase(Locale)
2518 public String toLowerCase() {
2519 throw new UnsupportedOperationException("Should be supported but without connection to locale");
2523 * Converts all of the characters in this <code>String</code> to upper
2524 * case using the rules of the given <code>Locale</code>. Case mapping is based
2525 * on the Unicode Standard version specified by the {@link java.lang.Character Character}
2526 * class. Since case mappings are not always 1:1 char mappings, the resulting
2527 * <code>String</code> may be a different length than the original <code>String</code>.
2529 * Examples of locale-sensitive and 1:M case mappings are in the following table.
2531 * <table border="1" summary="Examples of locale-sensitive and 1:M case mappings. Shows Language code of locale, lower case, upper case, and description.">
2533 * <th>Language Code of Locale</th>
2534 * <th>Lower Case</th>
2535 * <th>Upper Case</th>
2536 * <th>Description</th>
2539 * <td>tr (Turkish)</td>
2540 * <td>\u0069</td>
2541 * <td>\u0130</td>
2542 * <td>small letter i -> capital letter I with dot above</td>
2545 * <td>tr (Turkish)</td>
2546 * <td>\u0131</td>
2547 * <td>\u0049</td>
2548 * <td>small letter dotless i -> capital letter I</td>
2552 * <td>\u00df</td>
2553 * <td>\u0053 \u0053</td>
2554 * <td>small letter sharp s -> two letters: SS</td>
2558 * <td>Fahrvergnügen</td>
2559 * <td>FAHRVERGNÜGEN</td>
2563 * @param locale use the case transformation rules for this locale
2564 * @return the <code>String</code>, converted to uppercase.
2565 * @see java.lang.String#toUpperCase()
2566 * @see java.lang.String#toLowerCase()
2567 * @see java.lang.String#toLowerCase(Locale)
2570 /* not for javascript
2571 public String toUpperCase(Locale locale) {
2572 if (locale == null) {
2573 throw new NullPointerException();
2578 // Now check if there are any characters that need to be changed.
2580 for (firstLower = 0 ; firstLower < count; ) {
2581 int c = (int)value[offset+firstLower];
2583 if ((c >= Character.MIN_HIGH_SURROGATE) &&
2584 (c <= Character.MAX_HIGH_SURROGATE)) {
2585 c = codePointAt(firstLower);
2586 srcCount = Character.charCount(c);
2590 int upperCaseChar = Character.toUpperCaseEx(c);
2591 if ((upperCaseChar == Character.ERROR) ||
2592 (c != upperCaseChar)) {
2595 firstLower += srcCount;
2600 char[] result = new char[count]; /* may grow *
2601 int resultOffset = 0; /* result may grow, so i+resultOffset
2602 * is the write location in result *
2604 /* Just copy the first few upperCase characters. *
2605 System.arraycopy(value, offset, result, 0, firstLower);
2607 String lang = locale.getLanguage();
2608 boolean localeDependent =
2609 (lang == "tr" || lang == "az" || lang == "lt");
2610 char[] upperCharArray;
2614 for (int i = firstLower; i < count; i += srcCount) {
2615 srcChar = (int)value[offset+i];
2616 if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
2617 (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
2618 srcChar = codePointAt(i);
2619 srcCount = Character.charCount(srcChar);
2623 if (localeDependent) {
2624 upperChar = ConditionalSpecialCasing.toUpperCaseEx(this, i, locale);
2626 upperChar = Character.toUpperCaseEx(srcChar);
2628 if ((upperChar == Character.ERROR) ||
2629 (upperChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
2630 if (upperChar == Character.ERROR) {
2631 if (localeDependent) {
2633 ConditionalSpecialCasing.toUpperCaseCharArray(this, i, locale);
2635 upperCharArray = Character.toUpperCaseCharArray(srcChar);
2637 } else if (srcCount == 2) {
2638 resultOffset += Character.toChars(upperChar, result, i + resultOffset) - srcCount;
2641 upperCharArray = Character.toChars(upperChar);
2644 /* Grow result if needed *
2645 int mapLen = upperCharArray.length;
2646 if (mapLen > srcCount) {
2647 char[] result2 = new char[result.length + mapLen - srcCount];
2648 System.arraycopy(result, 0, result2, 0,
2652 for (int x=0; x<mapLen; ++x) {
2653 result[i+resultOffset+x] = upperCharArray[x];
2655 resultOffset += (mapLen - srcCount);
2657 result[i+resultOffset] = (char)upperChar;
2660 return new String(0, count+resultOffset, result);
2665 * Converts all of the characters in this <code>String</code> to upper
2666 * case using the rules of the default locale. This method is equivalent to
2667 * <code>toUpperCase(Locale.getDefault())</code>.
2669 * <b>Note:</b> This method is locale sensitive, and may produce unexpected
2670 * results if used for strings that are intended to be interpreted locale
2672 * Examples are programming language identifiers, protocol keys, and HTML
2674 * For instance, <code>"title".toUpperCase()</code> in a Turkish locale
2675 * returns <code>"T\u005Cu0130TLE"</code>, where '\u005Cu0130' is the
2676 * LATIN CAPITAL LETTER I WITH DOT ABOVE character.
2677 * To obtain correct results for locale insensitive strings, use
2678 * <code>toUpperCase(Locale.ENGLISH)</code>.
2680 * @return the <code>String</code>, converted to uppercase.
2681 * @see java.lang.String#toUpperCase(Locale)
2683 public String toUpperCase() {
2684 throw new UnsupportedOperationException();
2688 * Returns a copy of the string, with leading and trailing whitespace
2691 * If this <code>String</code> object represents an empty character
2692 * sequence, or the first and last characters of character sequence
2693 * represented by this <code>String</code> object both have codes
2694 * greater than <code>'\u0020'</code> (the space character), then a
2695 * reference to this <code>String</code> object is returned.
2697 * Otherwise, if there is no character with a code greater than
2698 * <code>'\u0020'</code> in the string, then a new
2699 * <code>String</code> object representing an empty string is created
2702 * Otherwise, let <i>k</i> be the index of the first character in the
2703 * string whose code is greater than <code>'\u0020'</code>, and let
2704 * <i>m</i> be the index of the last character in the string whose code
2705 * is greater than <code>'\u0020'</code>. A new <code>String</code>
2706 * object is created, representing the substring of this string that
2707 * begins with the character at index <i>k</i> and ends with the
2708 * character at index <i>m</i>-that is, the result of
2709 * <code>this.substring(<i>k</i>, <i>m</i>+1)</code>.
2711 * This method may be used to trim whitespace (as defined above) from
2712 * the beginning and end of a string.
2714 * @return A copy of this string with leading and trailing white
2715 * space removed, or this string if it has no leading or
2716 * trailing white space.
2718 public String trim() {
2721 int off = offset; /* avoid getfield opcode */
2722 char[] val = value; /* avoid getfield opcode */
2724 while ((st < len) && (val[off + st] <= ' ')) {
2727 while ((st < len) && (val[off + len - 1] <= ' ')) {
2730 return ((st > 0) || (len < count)) ? substring(st, len) : this;
2734 * This object (which is already a string!) is itself returned.
2736 * @return the string itself.
2738 public String toString() {
2743 * Converts this string to a new character array.
2745 * @return a newly allocated character array whose length is the length
2746 * of this string and whose contents are initialized to contain
2747 * the character sequence represented by this string.
2749 public char[] toCharArray() {
2750 char result[] = new char[count];
2751 getChars(0, count, result, 0);
2756 * Returns a formatted string using the specified format string and
2759 * <p> The locale always used is the one returned by {@link
2760 * java.util.Locale#getDefault() Locale.getDefault()}.
2763 * A <a href="../util/Formatter.html#syntax">format string</a>
2766 * Arguments referenced by the format specifiers in the format
2767 * string. If there are more arguments than format specifiers, the
2768 * extra arguments are ignored. The number of arguments is
2769 * variable and may be zero. The maximum number of arguments is
2770 * limited by the maximum dimension of a Java array as defined by
2771 * <cite>The Java™ Virtual Machine Specification</cite>.
2772 * The behaviour on a
2773 * <tt>null</tt> argument depends on the <a
2774 * href="../util/Formatter.html#syntax">conversion</a>.
2776 * @throws IllegalFormatException
2777 * If a format string contains an illegal syntax, a format
2778 * specifier that is incompatible with the given arguments,
2779 * insufficient arguments given the format string, or other
2780 * illegal conditions. For specification of all possible
2781 * formatting errors, see the <a
2782 * href="../util/Formatter.html#detail">Details</a> section of the
2783 * formatter class specification.
2785 * @throws NullPointerException
2786 * If the <tt>format</tt> is <tt>null</tt>
2788 * @return A formatted string
2790 * @see java.util.Formatter
2793 public static String format(String format, Object ... args) {
2794 throw new UnsupportedOperationException();
2798 * Returns a formatted string using the specified locale, format string,
2802 * The {@linkplain java.util.Locale locale} to apply during
2803 * formatting. If <tt>l</tt> is <tt>null</tt> then no localization
2807 * A <a href="../util/Formatter.html#syntax">format string</a>
2810 * Arguments referenced by the format specifiers in the format
2811 * string. If there are more arguments than format specifiers, the
2812 * extra arguments are ignored. The number of arguments is
2813 * variable and may be zero. The maximum number of arguments is
2814 * limited by the maximum dimension of a Java array as defined by
2815 * <cite>The Java™ Virtual Machine Specification</cite>.
2816 * The behaviour on a
2817 * <tt>null</tt> argument depends on the <a
2818 * href="../util/Formatter.html#syntax">conversion</a>.
2820 * @throws IllegalFormatException
2821 * If a format string contains an illegal syntax, a format
2822 * specifier that is incompatible with the given arguments,
2823 * insufficient arguments given the format string, or other
2824 * illegal conditions. For specification of all possible
2825 * formatting errors, see the <a
2826 * href="../util/Formatter.html#detail">Details</a> section of the
2827 * formatter class specification
2829 * @throws NullPointerException
2830 * If the <tt>format</tt> is <tt>null</tt>
2832 * @return A formatted string
2834 * @see java.util.Formatter
2837 // public static String format(Locale l, String format, Object ... args) {
2838 // return new Formatter(l).format(format, args).toString();
2842 * Returns the string representation of the <code>Object</code> argument.
2844 * @param obj an <code>Object</code>.
2845 * @return if the argument is <code>null</code>, then a string equal to
2846 * <code>"null"</code>; otherwise, the value of
2847 * <code>obj.toString()</code> is returned.
2848 * @see java.lang.Object#toString()
2850 public static String valueOf(Object obj) {
2851 return (obj == null) ? "null" : obj.toString();
2855 * Returns the string representation of the <code>char</code> array
2856 * argument. The contents of the character array are copied; subsequent
2857 * modification of the character array does not affect the newly
2860 * @param data a <code>char</code> array.
2861 * @return a newly allocated string representing the same sequence of
2862 * characters contained in the character array argument.
2864 public static String valueOf(char data[]) {
2865 return new String(data);
2869 * Returns the string representation of a specific subarray of the
2870 * <code>char</code> array argument.
2872 * The <code>offset</code> argument is the index of the first
2873 * character of the subarray. The <code>count</code> argument
2874 * specifies the length of the subarray. The contents of the subarray
2875 * are copied; subsequent modification of the character array does not
2876 * affect the newly created string.
2878 * @param data the character array.
2879 * @param offset the initial offset into the value of the
2880 * <code>String</code>.
2881 * @param count the length of the value of the <code>String</code>.
2882 * @return a string representing the sequence of characters contained
2883 * in the subarray of the character array argument.
2884 * @exception IndexOutOfBoundsException if <code>offset</code> is
2885 * negative, or <code>count</code> is negative, or
2886 * <code>offset+count</code> is larger than
2887 * <code>data.length</code>.
2889 public static String valueOf(char data[], int offset, int count) {
2890 return new String(data, offset, count);
2894 * Returns a String that represents the character sequence in the
2897 * @param data the character array.
2898 * @param offset initial offset of the subarray.
2899 * @param count length of the subarray.
2900 * @return a <code>String</code> that contains the characters of the
2901 * specified subarray of the character array.
2903 public static String copyValueOf(char data[], int offset, int count) {
2904 // All public String constructors now copy the data.
2905 return new String(data, offset, count);
2909 * Returns a String that represents the character sequence in the
2912 * @param data the character array.
2913 * @return a <code>String</code> that contains the characters of the
2916 public static String copyValueOf(char data[]) {
2917 return copyValueOf(data, 0, data.length);
2921 * Returns the string representation of the <code>boolean</code> argument.
2923 * @param b a <code>boolean</code>.
2924 * @return if the argument is <code>true</code>, a string equal to
2925 * <code>"true"</code> is returned; otherwise, a string equal to
2926 * <code>"false"</code> is returned.
2928 public static String valueOf(boolean b) {
2929 return b ? "true" : "false";
2933 * Returns the string representation of the <code>char</code>
2936 * @param c a <code>char</code>.
2937 * @return a string of length <code>1</code> containing
2938 * as its single character the argument <code>c</code>.
2940 public static String valueOf(char c) {
2942 return new String(0, 1, data);
2946 * Returns the string representation of the <code>int</code> argument.
2948 * The representation is exactly the one returned by the
2949 * <code>Integer.toString</code> method of one argument.
2951 * @param i an <code>int</code>.
2952 * @return a string representation of the <code>int</code> argument.
2953 * @see java.lang.Integer#toString(int, int)
2955 public static String valueOf(int i) {
2956 return Integer.toString(i);
2960 * Returns the string representation of the <code>long</code> argument.
2962 * The representation is exactly the one returned by the
2963 * <code>Long.toString</code> method of one argument.
2965 * @param l a <code>long</code>.
2966 * @return a string representation of the <code>long</code> argument.
2967 * @see java.lang.Long#toString(long)
2969 public static String valueOf(long l) {
2970 return Long.toString(l);
2974 * Returns the string representation of the <code>float</code> argument.
2976 * The representation is exactly the one returned by the
2977 * <code>Float.toString</code> method of one argument.
2979 * @param f a <code>float</code>.
2980 * @return a string representation of the <code>float</code> argument.
2981 * @see java.lang.Float#toString(float)
2983 public static String valueOf(float f) {
2984 return Float.toString(f);
2988 * Returns the string representation of the <code>double</code> argument.
2990 * The representation is exactly the one returned by the
2991 * <code>Double.toString</code> method of one argument.
2993 * @param d a <code>double</code>.
2994 * @return a string representation of the <code>double</code> argument.
2995 * @see java.lang.Double#toString(double)
2997 public static String valueOf(double d) {
2998 return Double.toString(d);
3002 * Returns a canonical representation for the string object.
3004 * A pool of strings, initially empty, is maintained privately by the
3005 * class <code>String</code>.
3007 * When the intern method is invoked, if the pool already contains a
3008 * string equal to this <code>String</code> object as determined by
3009 * the {@link #equals(Object)} method, then the string from the pool is
3010 * returned. Otherwise, this <code>String</code> object is added to the
3011 * pool and a reference to this <code>String</code> object is returned.
3013 * It follows that for any two strings <code>s</code> and <code>t</code>,
3014 * <code>s.intern() == t.intern()</code> is <code>true</code>
3015 * if and only if <code>s.equals(t)</code> is <code>true</code>.
3017 * All literal strings and string-valued constant expressions are
3018 * interned. String literals are defined in section 3.10.5 of the
3019 * <cite>The Java™ Language Specification</cite>.
3021 * @return a string that has the same contents as this string, but is
3022 * guaranteed to be from a pool of unique strings.
3024 public native String intern();
3026 static char[] copyOfRange(char[] original, int from, int to) {
3027 int newLength = to - from;
3028 if (newLength < 0) {
3029 throw new IllegalArgumentException(from + " > " + to);
3031 char[] copy = new char[newLength];
3032 System.arraycopy(original, from, copy, 0,
3033 Math.min(original.length - from, newLength));
3036 static char[] copyOf(char[] original, int newLength) {
3037 char[] copy = new char[newLength];
3038 System.arraycopy(original, 0, copy, 0,
3039 Math.min(original.length, newLength));