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;
30 import java.util.Locale;
31 import org.apidesign.bck2brwsr.core.ExtraJavaScript;
32 import org.apidesign.bck2brwsr.core.JavaScriptBody;
33 import org.apidesign.bck2brwsr.core.JavaScriptOnly;
34 import org.apidesign.bck2brwsr.core.JavaScriptPrototype;
35 import org.apidesign.bck2brwsr.emul.lang.System;
38 * The <code>String</code> class represents character strings. All
39 * string literals in Java programs, such as <code>"abc"</code>, are
40 * implemented as instances of this class.
42 * Strings are constant; their values cannot be changed after they
43 * are created. String buffers support mutable strings.
44 * Because String objects are immutable they can be shared. For example:
45 * <p><blockquote><pre>
47 * </pre></blockquote><p>
49 * <p><blockquote><pre>
50 * char data[] = {'a', 'b', 'c'};
51 * String str = new String(data);
52 * </pre></blockquote><p>
53 * Here are some more examples of how strings can be used:
54 * <p><blockquote><pre>
55 * System.out.println("abc");
57 * System.out.println("abc" + cde);
58 * String c = "abc".substring(2,3);
59 * String d = cde.substring(1, 2);
62 * The class <code>String</code> includes methods for examining
63 * individual characters of the sequence, for comparing strings, for
64 * searching strings, for extracting substrings, and for creating a
65 * copy of a string with all characters translated to uppercase or to
66 * lowercase. Case mapping is based on the Unicode Standard version
67 * specified by the {@link java.lang.Character Character} class.
69 * The Java language provides special support for the string
70 * concatenation operator ( + ), and for conversion of
71 * other objects to strings. String concatenation is implemented
72 * through the <code>StringBuilder</code>(or <code>StringBuffer</code>)
73 * class and its <code>append</code> method.
74 * String conversions are implemented through the method
75 * <code>toString</code>, defined by <code>Object</code> and
76 * inherited by all classes in Java. For additional information on
77 * string concatenation and conversion, see Gosling, Joy, and Steele,
78 * <i>The Java Language Specification</i>.
80 * <p> Unless otherwise noted, passing a <tt>null</tt> argument to a constructor
81 * or method in this class will cause a {@link NullPointerException} to be
84 * <p>A <code>String</code> represents a string in the UTF-16 format
85 * in which <em>supplementary characters</em> are represented by <em>surrogate
86 * pairs</em> (see the section <a href="Character.html#unicode">Unicode
87 * Character Representations</a> in the <code>Character</code> class for
89 * Index values refer to <code>char</code> code units, so a supplementary
90 * character uses two positions in a <code>String</code>.
91 * <p>The <code>String</code> class provides methods for dealing with
92 * Unicode code points (i.e., characters), in addition to those for
93 * dealing with Unicode code units (i.e., <code>char</code> values).
96 * @author Arthur van Hoff
97 * @author Martin Buchholz
99 * @see java.lang.Object#toString()
100 * @see java.lang.StringBuffer
101 * @see java.lang.StringBuilder
102 * @see java.nio.charset.Charset
107 resource="/org/apidesign/vm4brwsr/emul/lang/java_lang_String.js",
110 @JavaScriptPrototype(container = "String.prototype", prototype = "new String")
111 public final class String
112 implements java.io.Serializable, Comparable<String>, CharSequence
114 /** real string to delegate to */
117 /** use serialVersionUID from JDK 1.0.2 for interoperability */
118 private static final long serialVersionUID = -6849794470754667710L;
123 @JavaScriptBody(args = {}, body =
124 "var p = vm.java_lang_String(false);\n"
125 + "p.toString = function() {\nreturn this._r().toString();\n};\n"
126 + "p.valueOf = function() {\nreturn this._r().valueOf();\n}\n"
128 private static native void registerToString();
131 * Class String is special cased within the Serialization Stream Protocol.
133 * A String instance is written initially into an ObjectOutputStream in the
136 * <code>TC_STRING</code> (utf String)
138 * The String is written by method <code>DataOutput.writeUTF</code>.
139 * A new handle is generated to refer to all future references to the
140 * string instance within the stream.
142 // private static final ObjectStreamField[] serialPersistentFields =
143 // new ObjectStreamField[0];
146 * Initializes a newly created {@code String} object so that it represents
147 * an empty character sequence. Note that use of this constructor is
148 * unnecessary since Strings are immutable.
155 * Initializes a newly created {@code String} object so that it represents
156 * the same sequence of characters as the argument; in other words, the
157 * newly created string is a copy of the argument string. Unless an
158 * explicit copy of {@code original} is needed, use of this constructor is
159 * unnecessary since Strings are immutable.
164 public String(String original) {
165 this.r = original.toString();
169 * Allocates a new {@code String} so that it represents the sequence of
170 * characters currently contained in the character array argument. The
171 * contents of the character array are copied; subsequent modification of
172 * the character array does not affect the newly created string.
175 * The initial value of the string
177 @JavaScriptBody(args = { "charArr" }, body=
178 "for (var i = 0; i < charArr.length; i++) {\n"
179 + " if (typeof charArr[i] === 'number') charArr[i] = String.fromCharCode(charArr[i]);\n"
181 + "this._r(charArr.join(''));\n"
183 public String(char value[]) {
187 * Allocates a new {@code String} that contains characters from a subarray
188 * of the character array argument. The {@code offset} argument is the
189 * index of the first character of the subarray and the {@code count}
190 * argument specifies the length of the subarray. The contents of the
191 * subarray are copied; subsequent modification of the character array does
192 * not affect the newly created string.
195 * Array that is the source of characters
203 * @throws IndexOutOfBoundsException
204 * If the {@code offset} and {@code count} arguments index
205 * characters outside the bounds of the {@code value} array
207 public String(char value[], int offset, int count) {
208 initFromCharArray(value, offset, count);
211 @JavaScriptBody(args = { "charArr", "off", "cnt" }, body =
212 "var up = off + cnt;\n" +
213 "for (var i = off; i < up; i++) {\n" +
214 " if (typeof charArr[i] === 'number') charArr[i] = String.fromCharCode(charArr[i]);\n" +
216 "this._r(charArr.slice(off, up).join(\"\"));\n"
218 private native void initFromCharArray(char value[], int offset, int count);
221 * Allocates a new {@code String} that contains characters from a subarray
222 * of the <a href="Character.html#unicode">Unicode code point</a> array
223 * argument. The {@code offset} argument is the index of the first code
224 * point of the subarray and the {@code count} argument specifies the
225 * length of the subarray. The contents of the subarray are converted to
226 * {@code char}s; subsequent modification of the {@code int} array does not
227 * affect the newly created string.
230 * Array that is the source of Unicode code points
238 * @throws IllegalArgumentException
239 * If any invalid Unicode code point is found in {@code
242 * @throws IndexOutOfBoundsException
243 * If the {@code offset} and {@code count} arguments index
244 * characters outside the bounds of the {@code codePoints} array
248 public String(int[] codePoints, int offset, int count) {
250 throw new StringIndexOutOfBoundsException(offset);
253 throw new StringIndexOutOfBoundsException(count);
255 // Note: offset or count might be near -1>>>1.
256 if (offset > codePoints.length - count) {
257 throw new StringIndexOutOfBoundsException(offset + count);
260 final int end = offset + count;
262 // Pass 1: Compute precise size of char[]
264 for (int i = offset; i < end; i++) {
265 int c = codePoints[i];
266 if (Character.isBmpCodePoint(c))
268 else if (Character.isValidCodePoint(c))
270 else throw new IllegalArgumentException(Integer.toString(c));
273 // Pass 2: Allocate and fill in char[]
274 final char[] v = new char[n];
276 for (int i = offset, j = 0; i < end; i++, j++) {
277 int c = codePoints[i];
278 if (Character.isBmpCodePoint(c))
281 Character.toSurrogates(c, v, j++);
284 this.r = new String(v, 0, n);
288 * Allocates a new {@code String} constructed from a subarray of an array
289 * of 8-bit integer values.
291 * <p> The {@code offset} argument is the index of the first byte of the
292 * subarray, and the {@code count} argument specifies the length of the
295 * <p> Each {@code byte} in the subarray is converted to a {@code char} as
296 * specified in the method above.
298 * @deprecated This method does not properly convert bytes into characters.
299 * As of JDK 1.1, the preferred way to do this is via the
300 * {@code String} constructors that take a {@link
301 * java.nio.charset.Charset}, charset name, or that use the platform's
305 * The bytes to be converted to characters
308 * The top 8 bits of each 16-bit Unicode code unit
315 * @throws IndexOutOfBoundsException
316 * If the {@code offset} or {@code count} argument is invalid
318 * @see #String(byte[], int)
319 * @see #String(byte[], int, int, java.lang.String)
320 * @see #String(byte[], int, int, java.nio.charset.Charset)
321 * @see #String(byte[], int, int)
322 * @see #String(byte[], java.lang.String)
323 * @see #String(byte[], java.nio.charset.Charset)
324 * @see #String(byte[])
327 public String(byte ascii[], int hibyte, int offset, int count) {
328 checkBounds(ascii, offset, count);
329 char value[] = new char[count];
332 for (int i = count ; i-- > 0 ;) {
333 value[i] = (char) (ascii[i + offset] & 0xff);
337 for (int i = count ; i-- > 0 ;) {
338 value[i] = (char) (hibyte | (ascii[i + offset] & 0xff));
341 initFromCharArray(value, offset, count);
345 * Allocates a new {@code String} containing characters constructed from
346 * an array of 8-bit integer values. Each character <i>c</i>in the
347 * resulting string is constructed from the corresponding component
348 * <i>b</i> in the byte array such that:
351 * <b><i>c</i></b> == (char)(((hibyte & 0xff) << 8)
352 * | (<b><i>b</i></b> & 0xff))
353 * </pre></blockquote>
355 * @deprecated This method does not properly convert bytes into
356 * characters. As of JDK 1.1, the preferred way to do this is via the
357 * {@code String} constructors that take a {@link
358 * java.nio.charset.Charset}, charset name, or that use the platform's
362 * The bytes to be converted to characters
365 * The top 8 bits of each 16-bit Unicode code unit
367 * @see #String(byte[], int, int, java.lang.String)
368 * @see #String(byte[], int, int, java.nio.charset.Charset)
369 * @see #String(byte[], int, int)
370 * @see #String(byte[], java.lang.String)
371 * @see #String(byte[], java.nio.charset.Charset)
372 * @see #String(byte[])
375 public String(byte ascii[], int hibyte) {
376 this(ascii, hibyte, 0, ascii.length);
379 /* Common private utility method used to bounds check the byte array
380 * and requested offset & length values used by the String(byte[],..)
383 private static void checkBounds(byte[] bytes, int offset, int length) {
385 throw new StringIndexOutOfBoundsException(length);
387 throw new StringIndexOutOfBoundsException(offset);
388 if (offset > bytes.length - length)
389 throw new StringIndexOutOfBoundsException(offset + length);
393 * Constructs a new {@code String} by decoding the specified subarray of
394 * bytes using the specified charset. The length of the new {@code String}
395 * is a function of the charset, and hence may not be equal to the length
398 * <p> The behavior of this constructor when the given bytes are not valid
399 * in the given charset is unspecified. The {@link
400 * java.nio.charset.CharsetDecoder} class should be used when more control
401 * over the decoding process is required.
404 * The bytes to be decoded into characters
407 * The index of the first byte to decode
410 * The number of bytes to decode
413 * The name of a supported {@linkplain java.nio.charset.Charset
416 * @throws UnsupportedEncodingException
417 * If the named charset is not supported
419 * @throws IndexOutOfBoundsException
420 * If the {@code offset} and {@code length} arguments index
421 * characters outside the bounds of the {@code bytes} array
425 public String(byte bytes[], int offset, int length, String charsetName)
426 throws UnsupportedEncodingException
428 this(checkUTF8(bytes, charsetName), offset, length);
432 * Constructs a new {@code String} by decoding the specified subarray of
433 * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
434 * The length of the new {@code String} is a function of the charset, and
435 * hence may not be equal to the length of the subarray.
437 * <p> This method always replaces malformed-input and unmappable-character
438 * sequences with this charset's default replacement string. The {@link
439 * java.nio.charset.CharsetDecoder} class should be used when more control
440 * over the decoding process is required.
443 * The bytes to be decoded into characters
446 * The index of the first byte to decode
449 * The number of bytes to decode
452 * The {@linkplain java.nio.charset.Charset charset} to be used to
453 * decode the {@code bytes}
455 * @throws IndexOutOfBoundsException
456 * If the {@code offset} and {@code length} arguments index
457 * characters outside the bounds of the {@code bytes} array
461 /* don't want dependnecy on Charset
462 public String(byte bytes[], int offset, int length, Charset charset) {
464 throw new NullPointerException("charset");
465 checkBounds(bytes, offset, length);
466 char[] v = StringCoding.decode(charset, bytes, offset, length);
468 this.count = v.length;
474 * Constructs a new {@code String} by decoding the specified array of bytes
475 * using the specified {@linkplain java.nio.charset.Charset charset}. The
476 * length of the new {@code String} is a function of the charset, and hence
477 * may not be equal to the length of the byte array.
479 * <p> The behavior of this constructor when the given bytes are not valid
480 * in the given charset is unspecified. The {@link
481 * java.nio.charset.CharsetDecoder} class should be used when more control
482 * over the decoding process is required.
485 * The bytes to be decoded into characters
488 * The name of a supported {@linkplain java.nio.charset.Charset
491 * @throws UnsupportedEncodingException
492 * If the named charset is not supported
496 public String(byte bytes[], String charsetName)
497 throws UnsupportedEncodingException
499 this(bytes, 0, bytes.length, charsetName);
503 * Constructs a new {@code String} by decoding the specified array of
504 * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
505 * The length of the new {@code String} is a function of the charset, and
506 * hence may not be equal to the length of the byte array.
508 * <p> This method always replaces malformed-input and unmappable-character
509 * sequences with this charset's default replacement string. The {@link
510 * java.nio.charset.CharsetDecoder} class should be used when more control
511 * over the decoding process is required.
514 * The bytes to be decoded into characters
517 * The {@linkplain java.nio.charset.Charset charset} to be used to
518 * decode the {@code bytes}
522 /* don't want dep on Charset
523 public String(byte bytes[], Charset charset) {
524 this(bytes, 0, bytes.length, charset);
529 * Constructs a new {@code String} by decoding the specified subarray of
530 * bytes using the platform's default charset. The length of the new
531 * {@code String} is a function of the charset, and hence may not be equal
532 * to the length of the subarray.
534 * <p> The behavior of this constructor when the given bytes are not valid
535 * in the default charset is unspecified. The {@link
536 * java.nio.charset.CharsetDecoder} class should be used when more control
537 * over the decoding process is required.
540 * The bytes to be decoded into characters
543 * The index of the first byte to decode
546 * The number of bytes to decode
548 * @throws IndexOutOfBoundsException
549 * If the {@code offset} and the {@code length} arguments index
550 * characters outside the bounds of the {@code bytes} array
554 public String(byte bytes[], int offset, int length) {
555 checkBounds(bytes, offset, length);
556 char[] v = new char[length];
557 int[] at = { offset };
558 int end = offset + length;
560 while (at[0] < end) {
561 int ch = nextChar(bytes, at);
562 v[chlen++] = (char)ch;
564 initFromCharArray(v, 0, chlen);
568 * Constructs a new {@code String} by decoding the specified array of bytes
569 * using the platform's default charset. The length of the new {@code
570 * String} is a function of the charset, and hence may not be equal to the
571 * length of the byte array.
573 * <p> The behavior of this constructor when the given bytes are not valid
574 * in the default charset is unspecified. The {@link
575 * java.nio.charset.CharsetDecoder} class should be used when more control
576 * over the decoding process is required.
579 * The bytes to be decoded into characters
583 public String(byte bytes[]) {
584 this(bytes, 0, bytes.length);
588 * Allocates a new string that contains the sequence of characters
589 * currently contained in the string buffer argument. The contents of the
590 * string buffer are copied; subsequent modification of the string buffer
591 * does not affect the newly created string.
594 * A {@code StringBuffer}
596 public String(StringBuffer buffer) {
597 this.r = buffer.toString();
601 * Allocates a new string that contains the sequence of characters
602 * currently contained in the string builder argument. The contents of the
603 * string builder are copied; subsequent modification of the string builder
604 * does not affect the newly created string.
606 * <p> This constructor is provided to ease migration to {@code
607 * StringBuilder}. Obtaining a string from a string builder via the {@code
608 * toString} method is likely to run faster and is generally preferred.
611 * A {@code StringBuilder}
615 public String(StringBuilder builder) {
616 this.r = builder.toString();
620 * Returns the length of this string.
621 * The length is equal to the number of <a href="Character.html#unicode">Unicode
622 * code units</a> in the string.
624 * @return the length of the sequence of characters represented by this
627 @JavaScriptBody(args = {}, body = "return this.toString().length;")
628 public int length() {
629 throw new UnsupportedOperationException();
633 * Returns <tt>true</tt> if, and only if, {@link #length()} is <tt>0</tt>.
635 * @return <tt>true</tt> if {@link #length()} is <tt>0</tt>, otherwise
640 @JavaScriptBody(args = {}, body="return this.toString().length === 0;")
641 public boolean isEmpty() {
642 return length() == 0;
646 * Returns the <code>char</code> value at the
647 * specified index. An index ranges from <code>0</code> to
648 * <code>length() - 1</code>. The first <code>char</code> value of the sequence
649 * is at index <code>0</code>, the next at index <code>1</code>,
650 * and so on, as for array indexing.
652 * <p>If the <code>char</code> value specified by the index is a
653 * <a href="Character.html#unicode">surrogate</a>, the surrogate
656 * @param index the index of the <code>char</code> value.
657 * @return the <code>char</code> value at the specified index of this string.
658 * The first <code>char</code> value is at index <code>0</code>.
659 * @exception IndexOutOfBoundsException if the <code>index</code>
660 * argument is negative or not less than the length of this
663 @JavaScriptBody(args = { "index" },
664 body = "return this.toString().charCodeAt(index);"
666 public char charAt(int index) {
667 throw new UnsupportedOperationException();
671 * Returns the character (Unicode code point) at the specified
672 * index. The index refers to <code>char</code> values
673 * (Unicode code units) and ranges from <code>0</code> to
674 * {@link #length()}<code> - 1</code>.
676 * <p> If the <code>char</code> value specified at the given index
677 * is in the high-surrogate range, the following index is less
678 * than the length of this <code>String</code>, and the
679 * <code>char</code> value at the following index is in the
680 * low-surrogate range, then the supplementary code point
681 * corresponding to this surrogate pair is returned. Otherwise,
682 * the <code>char</code> value at the given index is returned.
684 * @param index the index to the <code>char</code> values
685 * @return the code point value of the character at the
687 * @exception IndexOutOfBoundsException if the <code>index</code>
688 * argument is negative or not less than the length of this
692 public int codePointAt(int index) {
693 if ((index < 0) || (index >= length())) {
694 throw new StringIndexOutOfBoundsException(index);
696 return Character.codePointAtImpl(toCharArray(), offset() + index, offset() + length());
700 * Returns the character (Unicode code point) before the specified
701 * index. The index refers to <code>char</code> values
702 * (Unicode code units) and ranges from <code>1</code> to {@link
703 * CharSequence#length() length}.
705 * <p> If the <code>char</code> value at <code>(index - 1)</code>
706 * is in the low-surrogate range, <code>(index - 2)</code> is not
707 * negative, and the <code>char</code> value at <code>(index -
708 * 2)</code> is in the high-surrogate range, then the
709 * supplementary code point value of the surrogate pair is
710 * returned. If the <code>char</code> value at <code>index -
711 * 1</code> is an unpaired low-surrogate or a high-surrogate, the
712 * surrogate value is returned.
714 * @param index the index following the code point that should be returned
715 * @return the Unicode code point value before the given index.
716 * @exception IndexOutOfBoundsException if the <code>index</code>
717 * argument is less than 1 or greater than the length
721 public int codePointBefore(int index) {
723 if ((i < 0) || (i >= length())) {
724 throw new StringIndexOutOfBoundsException(index);
726 return Character.codePointBeforeImpl(toCharArray(), offset() + index, offset());
730 * Returns the number of Unicode code points in the specified text
731 * range of this <code>String</code>. The text range begins at the
732 * specified <code>beginIndex</code> and extends to the
733 * <code>char</code> at index <code>endIndex - 1</code>. Thus the
734 * length (in <code>char</code>s) of the text range is
735 * <code>endIndex-beginIndex</code>. Unpaired surrogates within
736 * the text range count as one code point each.
738 * @param beginIndex the index to the first <code>char</code> of
740 * @param endIndex the index after the last <code>char</code> of
742 * @return the number of Unicode code points in the specified text
744 * @exception IndexOutOfBoundsException if the
745 * <code>beginIndex</code> is negative, or <code>endIndex</code>
746 * is larger than the length of this <code>String</code>, or
747 * <code>beginIndex</code> is larger than <code>endIndex</code>.
750 public int codePointCount(int beginIndex, int endIndex) {
751 if (beginIndex < 0 || endIndex > length() || beginIndex > endIndex) {
752 throw new IndexOutOfBoundsException();
754 return Character.codePointCountImpl(toCharArray(), offset()+beginIndex, endIndex-beginIndex);
758 * Returns the index within this <code>String</code> that is
759 * offset from the given <code>index</code> by
760 * <code>codePointOffset</code> code points. Unpaired surrogates
761 * within the text range given by <code>index</code> and
762 * <code>codePointOffset</code> count as one code point each.
764 * @param index the index to be offset
765 * @param codePointOffset the offset in code points
766 * @return the index within this <code>String</code>
767 * @exception IndexOutOfBoundsException if <code>index</code>
768 * is negative or larger then the length of this
769 * <code>String</code>, or if <code>codePointOffset</code> is positive
770 * and the substring starting with <code>index</code> has fewer
771 * than <code>codePointOffset</code> code points,
772 * or if <code>codePointOffset</code> is negative and the substring
773 * before <code>index</code> has fewer than the absolute value
774 * of <code>codePointOffset</code> code points.
777 public int offsetByCodePoints(int index, int codePointOffset) {
778 if (index < 0 || index > length()) {
779 throw new IndexOutOfBoundsException();
781 return Character.offsetByCodePointsImpl(toCharArray(), offset(), length(),
782 offset()+index, codePointOffset) - offset();
786 * Copy characters from this string into dst starting at dstBegin.
787 * This method doesn't perform any range checking.
789 @JavaScriptBody(args = { "arr", "to" }, body =
790 "var s = this.toString();\n" +
791 "for (var i = 0; i < s.length; i++) {\n" +
792 " arr[to++] = s[i];\n" +
795 void getChars(char dst[], int dstBegin) {
796 System.arraycopy(toCharArray(), offset(), dst, dstBegin, length());
800 * Copies characters from this string into the destination character
803 * The first character to be copied is at index <code>srcBegin</code>;
804 * the last character to be copied is at index <code>srcEnd-1</code>
805 * (thus the total number of characters to be copied is
806 * <code>srcEnd-srcBegin</code>). The characters are copied into the
807 * subarray of <code>dst</code> starting at index <code>dstBegin</code>
808 * and ending at index:
809 * <p><blockquote><pre>
810 * dstbegin + (srcEnd-srcBegin) - 1
811 * </pre></blockquote>
813 * @param srcBegin index of the first character in the string
815 * @param srcEnd index after the last character in the string
817 * @param dst the destination array.
818 * @param dstBegin the start offset in the destination array.
819 * @exception IndexOutOfBoundsException If any of the following
821 * <ul><li><code>srcBegin</code> is negative.
822 * <li><code>srcBegin</code> is greater than <code>srcEnd</code>
823 * <li><code>srcEnd</code> is greater than the length of this
825 * <li><code>dstBegin</code> is negative
826 * <li><code>dstBegin+(srcEnd-srcBegin)</code> is larger than
827 * <code>dst.length</code></ul>
829 @JavaScriptBody(args = { "beg", "end", "arr", "dst" }, body=
830 "var s = this.toString();\n" +
831 "while (beg < end) {\n" +
832 " arr[dst++] = s.charCodeAt(beg++);\n" +
835 public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
837 throw new StringIndexOutOfBoundsException(srcBegin);
839 if (srcEnd > length()) {
840 throw new StringIndexOutOfBoundsException(srcEnd);
842 if (srcBegin > srcEnd) {
843 throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
845 System.arraycopy(toCharArray(), offset() + srcBegin, dst, dstBegin,
850 * Copies characters from this string into the destination byte array. Each
851 * byte receives the 8 low-order bits of the corresponding character. The
852 * eight high-order bits of each character are not copied and do not
853 * participate in the transfer in any way.
855 * <p> The first character to be copied is at index {@code srcBegin}; the
856 * last character to be copied is at index {@code srcEnd-1}. The total
857 * number of characters to be copied is {@code srcEnd-srcBegin}. The
858 * characters, converted to bytes, are copied into the subarray of {@code
859 * dst} starting at index {@code dstBegin} and ending at index:
862 * dstbegin + (srcEnd-srcBegin) - 1
863 * </pre></blockquote>
865 * @deprecated This method does not properly convert characters into
866 * bytes. As of JDK 1.1, the preferred way to do this is via the
867 * {@link #getBytes()} method, which uses the platform's default charset.
870 * Index of the first character in the string to copy
873 * Index after the last character in the string to copy
876 * The destination array
879 * The start offset in the destination array
881 * @throws IndexOutOfBoundsException
882 * If any of the following is true:
884 * <li> {@code srcBegin} is negative
885 * <li> {@code srcBegin} is greater than {@code srcEnd}
886 * <li> {@code srcEnd} is greater than the length of this String
887 * <li> {@code dstBegin} is negative
888 * <li> {@code dstBegin+(srcEnd-srcBegin)} is larger than {@code
893 public void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin) {
895 throw new StringIndexOutOfBoundsException(srcBegin);
897 if (srcEnd > length()) {
898 throw new StringIndexOutOfBoundsException(srcEnd);
900 if (srcBegin > srcEnd) {
901 throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
904 int n = offset() + srcEnd;
905 int i = offset() + srcBegin;
906 char[] val = toCharArray(); /* avoid getfield opcode */
909 dst[j++] = (byte)val[i++];
914 * Encodes this {@code String} into a sequence of bytes using the named
915 * charset, storing the result into a new byte array.
917 * <p> The behavior of this method when this string cannot be encoded in
918 * the given charset is unspecified. The {@link
919 * java.nio.charset.CharsetEncoder} class should be used when more control
920 * over the encoding process is required.
923 * The name of a supported {@linkplain java.nio.charset.Charset
926 * @return The resultant byte array
928 * @throws UnsupportedEncodingException
929 * If the named charset is not supported
933 public byte[] getBytes(String charsetName)
934 throws UnsupportedEncodingException
936 checkUTF8(null, charsetName);
941 * Encodes this {@code String} into a sequence of bytes using the given
942 * {@linkplain java.nio.charset.Charset charset}, storing the result into a
945 * <p> This method always replaces malformed-input and unmappable-character
946 * sequences with this charset's default replacement byte array. The
947 * {@link java.nio.charset.CharsetEncoder} class should be used when more
948 * control over the encoding process is required.
951 * The {@linkplain java.nio.charset.Charset} to be used to encode
954 * @return The resultant byte array
958 /* don't want dep on Charset
959 public byte[] getBytes(Charset charset) {
960 if (charset == null) throw new NullPointerException();
961 return StringCoding.encode(charset, value, offset, count);
966 * Encodes this {@code String} into a sequence of bytes using the
967 * platform's default charset, storing the result into a new byte array.
969 * <p> The behavior of this method when this string cannot be encoded in
970 * the default charset is unspecified. The {@link
971 * java.nio.charset.CharsetEncoder} class should be used when more control
972 * over the encoding process is required.
974 * @return The resultant byte array
978 public byte[] getBytes() {
980 byte[] arr = new byte[len];
981 for (int i = 0, j = 0; j < len; j++) {
982 final int v = charAt(j);
988 arr = System.expandArray(arr, i + 1);
989 arr[i++] = (byte) (0xC0 | (v >> 6));
990 arr[i++] = (byte) (0x80 | (0x3F & v));
993 arr = System.expandArray(arr, i + 2);
994 arr[i++] = (byte) (0xE0 | (v >> 12));
995 arr[i++] = (byte) (0x80 | ((v >> 6) & 0x7F));
996 arr[i++] = (byte) (0x80 | (0x3F & v));
1002 * Compares this string to the specified object. The result is {@code
1003 * true} if and only if the argument is not {@code null} and is a {@code
1004 * String} object that represents the same sequence of characters as this
1008 * The object to compare this {@code String} against
1010 * @return {@code true} if the given object represents a {@code String}
1011 * equivalent to this string, {@code false} otherwise
1013 * @see #compareTo(String)
1014 * @see #equalsIgnoreCase(String)
1016 @JavaScriptBody(args = { "obj" }, body =
1017 "return obj != null && obj.$instOf_java_lang_String && "
1018 + "this.toString() === obj.toString();"
1020 public boolean equals(Object anObject) {
1021 if (this == anObject) {
1024 if (anObject instanceof String) {
1025 String anotherString = (String)anObject;
1027 if (n == anotherString.length()) {
1028 char v1[] = toCharArray();
1029 char v2[] = anotherString.toCharArray();
1031 int j = anotherString.offset();
1033 if (v1[i++] != v2[j++])
1043 * Compares this string to the specified {@code StringBuffer}. The result
1044 * is {@code true} if and only if this {@code String} represents the same
1045 * sequence of characters as the specified {@code StringBuffer}.
1048 * The {@code StringBuffer} to compare this {@code String} against
1050 * @return {@code true} if this {@code String} represents the same
1051 * sequence of characters as the specified {@code StringBuffer},
1052 * {@code false} otherwise
1056 public boolean contentEquals(StringBuffer sb) {
1058 return contentEquals((CharSequence)sb);
1063 * Compares this string to the specified {@code CharSequence}. The result
1064 * is {@code true} if and only if this {@code String} represents the same
1065 * sequence of char values as the specified sequence.
1068 * The sequence to compare this {@code String} against
1070 * @return {@code true} if this {@code String} represents the same
1071 * sequence of char values as the specified sequence, {@code
1076 public boolean contentEquals(CharSequence cs) {
1077 if (length() != cs.length())
1079 // Argument is a StringBuffer, StringBuilder
1080 if (cs instanceof AbstractStringBuilder) {
1081 char v1[] = toCharArray();
1082 char v2[] = ((AbstractStringBuilder)cs).getValue();
1087 if (v1[i++] != v2[j++])
1092 // Argument is a String
1093 if (cs.equals(this))
1095 // Argument is a generic CharSequence
1096 char v1[] = toCharArray();
1101 if (v1[i++] != cs.charAt(j++))
1108 * Compares this {@code String} to another {@code String}, ignoring case
1109 * considerations. Two strings are considered equal ignoring case if they
1110 * are of the same length and corresponding characters in the two strings
1111 * are equal ignoring case.
1113 * <p> Two characters {@code c1} and {@code c2} are considered the same
1114 * ignoring case if at least one of the following is true:
1116 * <li> The two characters are the same (as compared by the
1117 * {@code ==} operator)
1118 * <li> Applying the method {@link
1119 * java.lang.Character#toUpperCase(char)} to each character
1120 * produces the same result
1121 * <li> Applying the method {@link
1122 * java.lang.Character#toLowerCase(char)} to each character
1123 * produces the same result
1126 * @param anotherString
1127 * The {@code String} to compare this {@code String} against
1129 * @return {@code true} if the argument is not {@code null} and it
1130 * represents an equivalent {@code String} ignoring case; {@code
1133 * @see #equals(Object)
1135 public boolean equalsIgnoreCase(String anotherString) {
1136 return (this == anotherString) ? true :
1137 (anotherString != null) && (anotherString.length() == length()) &&
1138 regionMatches(true, 0, anotherString, 0, length());
1142 * Compares two strings lexicographically.
1143 * The comparison is based on the Unicode value of each character in
1144 * the strings. The character sequence represented by this
1145 * <code>String</code> object is compared lexicographically to the
1146 * character sequence represented by the argument string. The result is
1147 * a negative integer if this <code>String</code> object
1148 * lexicographically precedes the argument string. The result is a
1149 * positive integer if this <code>String</code> object lexicographically
1150 * follows the argument string. The result is zero if the strings
1151 * are equal; <code>compareTo</code> returns <code>0</code> exactly when
1152 * the {@link #equals(Object)} method would return <code>true</code>.
1154 * This is the definition of lexicographic ordering. If two strings are
1155 * different, then either they have different characters at some index
1156 * that is a valid index for both strings, or their lengths are different,
1157 * or both. If they have different characters at one or more index
1158 * positions, let <i>k</i> be the smallest such index; then the string
1159 * whose character at position <i>k</i> has the smaller value, as
1160 * determined by using the < operator, lexicographically precedes the
1161 * other string. In this case, <code>compareTo</code> returns the
1162 * difference of the two character values at position <code>k</code> in
1163 * the two string -- that is, the value:
1165 * this.charAt(k)-anotherString.charAt(k)
1166 * </pre></blockquote>
1167 * If there is no index position at which they differ, then the shorter
1168 * string lexicographically precedes the longer string. In this case,
1169 * <code>compareTo</code> returns the difference of the lengths of the
1170 * strings -- that is, the value:
1172 * this.length()-anotherString.length()
1173 * </pre></blockquote>
1175 * @param anotherString the <code>String</code> to be compared.
1176 * @return the value <code>0</code> if the argument string is equal to
1177 * this string; a value less than <code>0</code> if this string
1178 * is lexicographically less than the string argument; and a
1179 * value greater than <code>0</code> if this string is
1180 * lexicographically greater than the string argument.
1182 public int compareTo(String anotherString) {
1183 int len1 = length();
1184 int len2 = anotherString.length();
1185 int n = Math.min(len1, len2);
1186 char v1[] = toCharArray();
1187 char v2[] = anotherString.toCharArray();
1189 int j = anotherString.offset();
1215 * A Comparator that orders <code>String</code> objects as by
1216 * <code>compareToIgnoreCase</code>. This comparator is serializable.
1218 * Note that this Comparator does <em>not</em> take locale into account,
1219 * and will result in an unsatisfactory ordering for certain locales.
1220 * The java.text package provides <em>Collators</em> to allow
1221 * locale-sensitive ordering.
1223 * @see java.text.Collator#compare(String, String)
1226 public static final Comparator<String> CASE_INSENSITIVE_ORDER
1227 = new CaseInsensitiveComparator();
1229 private static int offset() {
1233 private static class CaseInsensitiveComparator
1234 implements Comparator<String>, java.io.Serializable {
1235 // use serialVersionUID from JDK 1.2.2 for interoperability
1236 private static final long serialVersionUID = 8575799808933029326L;
1238 public int compare(String s1, String s2) {
1239 int n1 = s1.length();
1240 int n2 = s2.length();
1241 int min = Math.min(n1, n2);
1242 for (int i = 0; i < min; i++) {
1243 char c1 = s1.charAt(i);
1244 char c2 = s2.charAt(i);
1246 c1 = Character.toUpperCase(c1);
1247 c2 = Character.toUpperCase(c2);
1249 c1 = Character.toLowerCase(c1);
1250 c2 = Character.toLowerCase(c2);
1252 // No overflow because of numeric promotion
1263 * Compares two strings lexicographically, ignoring case
1264 * differences. This method returns an integer whose sign is that of
1265 * calling <code>compareTo</code> with normalized versions of the strings
1266 * where case differences have been eliminated by calling
1267 * <code>Character.toLowerCase(Character.toUpperCase(character))</code> on
1270 * Note that this method does <em>not</em> take locale into account,
1271 * and will result in an unsatisfactory ordering for certain locales.
1272 * The java.text package provides <em>collators</em> to allow
1273 * locale-sensitive ordering.
1275 * @param str the <code>String</code> to be compared.
1276 * @return a negative integer, zero, or a positive integer as the
1277 * specified String is greater than, equal to, or less
1278 * than this String, ignoring case considerations.
1279 * @see java.text.Collator#compare(String, String)
1282 public int compareToIgnoreCase(String str) {
1283 return CASE_INSENSITIVE_ORDER.compare(this, str);
1287 * Tests if two string regions are equal.
1289 * A substring of this <tt>String</tt> object is compared to a substring
1290 * of the argument other. The result is true if these substrings
1291 * represent identical character sequences. The substring of this
1292 * <tt>String</tt> object to be compared begins at index <tt>toffset</tt>
1293 * and has length <tt>len</tt>. The substring of other to be compared
1294 * begins at index <tt>ooffset</tt> and has length <tt>len</tt>. The
1295 * result is <tt>false</tt> if and only if at least one of the following
1297 * <ul><li><tt>toffset</tt> is negative.
1298 * <li><tt>ooffset</tt> is negative.
1299 * <li><tt>toffset+len</tt> is greater than the length of this
1300 * <tt>String</tt> object.
1301 * <li><tt>ooffset+len</tt> is greater than the length of the other
1303 * <li>There is some nonnegative integer <i>k</i> less than <tt>len</tt>
1305 * <tt>this.charAt(toffset+<i>k</i>) != other.charAt(ooffset+<i>k</i>)</tt>
1308 * @param toffset the starting offset of the subregion in this string.
1309 * @param other the string argument.
1310 * @param ooffset the starting offset of the subregion in the string
1312 * @param len the number of characters to compare.
1313 * @return <code>true</code> if the specified subregion of this string
1314 * exactly matches the specified subregion of the string argument;
1315 * <code>false</code> otherwise.
1317 public boolean regionMatches(int toffset, String other, int ooffset,
1319 char ta[] = toCharArray();
1320 int to = offset() + toffset;
1321 char pa[] = other.toCharArray();
1322 int po = other.offset() + ooffset;
1323 // Note: toffset, ooffset, or len might be near -1>>>1.
1324 if ((ooffset < 0) || (toffset < 0) || (toffset > (long)length() - len)
1325 || (ooffset > (long)other.length() - len)) {
1329 if (ta[to++] != pa[po++]) {
1337 * Tests if two string regions are equal.
1339 * A substring of this <tt>String</tt> object is compared to a substring
1340 * of the argument <tt>other</tt>. The result is <tt>true</tt> if these
1341 * substrings represent character sequences that are the same, ignoring
1342 * case if and only if <tt>ignoreCase</tt> is true. The substring of
1343 * this <tt>String</tt> object to be compared begins at index
1344 * <tt>toffset</tt> and has length <tt>len</tt>. The substring of
1345 * <tt>other</tt> to be compared begins at index <tt>ooffset</tt> and
1346 * has length <tt>len</tt>. The result is <tt>false</tt> if and only if
1347 * at least one of the following is true:
1348 * <ul><li><tt>toffset</tt> is negative.
1349 * <li><tt>ooffset</tt> is negative.
1350 * <li><tt>toffset+len</tt> is greater than the length of this
1351 * <tt>String</tt> object.
1352 * <li><tt>ooffset+len</tt> is greater than the length of the other
1354 * <li><tt>ignoreCase</tt> is <tt>false</tt> and there is some nonnegative
1355 * integer <i>k</i> less than <tt>len</tt> such that:
1357 * this.charAt(toffset+k) != other.charAt(ooffset+k)
1358 * </pre></blockquote>
1359 * <li><tt>ignoreCase</tt> is <tt>true</tt> and there is some nonnegative
1360 * integer <i>k</i> less than <tt>len</tt> such that:
1362 * Character.toLowerCase(this.charAt(toffset+k)) !=
1363 Character.toLowerCase(other.charAt(ooffset+k))
1364 * </pre></blockquote>
1367 * Character.toUpperCase(this.charAt(toffset+k)) !=
1368 * Character.toUpperCase(other.charAt(ooffset+k))
1369 * </pre></blockquote>
1372 * @param ignoreCase if <code>true</code>, ignore case when comparing
1374 * @param toffset the starting offset of the subregion in this
1376 * @param other the string argument.
1377 * @param ooffset the starting offset of the subregion in the string
1379 * @param len the number of characters to compare.
1380 * @return <code>true</code> if the specified subregion of this string
1381 * matches the specified subregion of the string argument;
1382 * <code>false</code> otherwise. Whether the matching is exact
1383 * or case insensitive depends on the <code>ignoreCase</code>
1386 public boolean regionMatches(boolean ignoreCase, int toffset,
1387 String other, int ooffset, int len) {
1388 char ta[] = toCharArray();
1389 int to = offset() + toffset;
1390 char pa[] = other.toCharArray();
1391 int po = other.offset() + ooffset;
1392 // Note: toffset, ooffset, or len might be near -1>>>1.
1393 if ((ooffset < 0) || (toffset < 0) || (toffset > (long)length() - len) ||
1394 (ooffset > (long)other.length() - len)) {
1404 // If characters don't match but case may be ignored,
1405 // try converting both characters to uppercase.
1406 // If the results match, then the comparison scan should
1408 char u1 = Character.toUpperCase(c1);
1409 char u2 = Character.toUpperCase(c2);
1413 // Unfortunately, conversion to uppercase does not work properly
1414 // for the Georgian alphabet, which has strange rules about case
1415 // conversion. So we need to make one last check before
1417 if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) {
1427 * Tests if the substring of this string beginning at the
1428 * specified index starts with the specified prefix.
1430 * @param prefix the prefix.
1431 * @param toffset where to begin looking in this string.
1432 * @return <code>true</code> if the character sequence represented by the
1433 * argument is a prefix of the substring of this object starting
1434 * at index <code>toffset</code>; <code>false</code> otherwise.
1435 * The result is <code>false</code> if <code>toffset</code> is
1436 * negative or greater than the length of this
1437 * <code>String</code> object; otherwise the result is the same
1438 * as the result of the expression
1440 * this.substring(toffset).startsWith(prefix)
1443 @JavaScriptBody(args = { "find", "from" }, body=
1444 "find = find.toString();\n" +
1445 "return this.toString().substring(from, from + find.length) === find;\n"
1447 public boolean startsWith(String prefix, int toffset) {
1448 char ta[] = toCharArray();
1449 int to = offset() + toffset;
1450 char pa[] = prefix.toCharArray();
1451 int po = prefix.offset();
1452 int pc = prefix.length();
1453 // Note: toffset might be near -1>>>1.
1454 if ((toffset < 0) || (toffset > length() - pc)) {
1458 if (ta[to++] != pa[po++]) {
1466 * Tests if this string starts with the specified prefix.
1468 * @param prefix the prefix.
1469 * @return <code>true</code> if the character sequence represented by the
1470 * argument is a prefix of the character sequence represented by
1471 * this string; <code>false</code> otherwise.
1472 * Note also that <code>true</code> will be returned if the
1473 * argument is an empty string or is equal to this
1474 * <code>String</code> object as determined by the
1475 * {@link #equals(Object)} method.
1478 public boolean startsWith(String prefix) {
1479 return startsWith(prefix, 0);
1483 * Tests if this string ends with the specified suffix.
1485 * @param suffix the suffix.
1486 * @return <code>true</code> if the character sequence represented by the
1487 * argument is a suffix of the character sequence represented by
1488 * this object; <code>false</code> otherwise. Note that the
1489 * result will be <code>true</code> if the argument is the
1490 * empty string or is equal to this <code>String</code> object
1491 * as determined by the {@link #equals(Object)} method.
1493 public boolean endsWith(String suffix) {
1494 return startsWith(suffix, length() - suffix.length());
1498 * Returns a hash code for this string. The hash code for a
1499 * <code>String</code> object is computed as
1501 * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
1502 * </pre></blockquote>
1503 * using <code>int</code> arithmetic, where <code>s[i]</code> is the
1504 * <i>i</i>th character of the string, <code>n</code> is the length of
1505 * the string, and <code>^</code> indicates exponentiation.
1506 * (The hash value of the empty string is zero.)
1508 * @return a hash code value for this object.
1510 public int hashCode() {
1511 return super.hashCode();
1513 int computeHashCode() {
1515 if (h == 0 && length() > 0) {
1519 for (int i = 0; i < len; i++) {
1520 h = 31*h + charAt(off++);
1527 * Returns the index within this string of the first occurrence of
1528 * the specified character. If a character with value
1529 * <code>ch</code> occurs in the character sequence represented by
1530 * this <code>String</code> object, then the index (in Unicode
1531 * code units) of the first such occurrence is returned. For
1532 * values of <code>ch</code> in the range from 0 to 0xFFFF
1533 * (inclusive), this is the smallest value <i>k</i> such that:
1535 * this.charAt(<i>k</i>) == ch
1536 * </pre></blockquote>
1537 * is true. For other values of <code>ch</code>, it is the
1538 * smallest value <i>k</i> such that:
1540 * this.codePointAt(<i>k</i>) == ch
1541 * </pre></blockquote>
1542 * is true. In either case, if no such character occurs in this
1543 * string, then <code>-1</code> is returned.
1545 * @param ch a character (Unicode code point).
1546 * @return the index of the first occurrence of the character in the
1547 * character sequence represented by this object, or
1548 * <code>-1</code> if the character does not occur.
1550 public int indexOf(int ch) {
1551 return indexOf(ch, 0);
1555 * Returns the index within this string of the first occurrence of the
1556 * specified character, starting the search at the specified index.
1558 * If a character with value <code>ch</code> occurs in the
1559 * character sequence represented by this <code>String</code>
1560 * object at an index no smaller than <code>fromIndex</code>, then
1561 * the index of the first such occurrence is returned. For values
1562 * of <code>ch</code> in the range from 0 to 0xFFFF (inclusive),
1563 * this is the smallest value <i>k</i> such that:
1565 * (this.charAt(<i>k</i>) == ch) && (<i>k</i> >= fromIndex)
1566 * </pre></blockquote>
1567 * is true. For other values of <code>ch</code>, it is the
1568 * smallest value <i>k</i> such that:
1570 * (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> >= fromIndex)
1571 * </pre></blockquote>
1572 * is true. In either case, if no such character occurs in this
1573 * string at or after position <code>fromIndex</code>, then
1574 * <code>-1</code> is returned.
1577 * There is no restriction on the value of <code>fromIndex</code>. If it
1578 * is negative, it has the same effect as if it were zero: this entire
1579 * string may be searched. If it is greater than the length of this
1580 * string, it has the same effect as if it were equal to the length of
1581 * this string: <code>-1</code> is returned.
1583 * <p>All indices are specified in <code>char</code> values
1584 * (Unicode code units).
1586 * @param ch a character (Unicode code point).
1587 * @param fromIndex the index to start the search from.
1588 * @return the index of the first occurrence of the character in the
1589 * character sequence represented by this object that is greater
1590 * than or equal to <code>fromIndex</code>, or <code>-1</code>
1591 * if the character does not occur.
1593 @JavaScriptBody(args = { "ch", "from" }, body =
1594 "if (typeof ch === 'number') ch = String.fromCharCode(ch);\n" +
1595 "return this.toString().indexOf(ch, from);\n"
1597 public int indexOf(int ch, int fromIndex) {
1598 if (fromIndex < 0) {
1600 } else if (fromIndex >= length()) {
1601 // Note: fromIndex might be near -1>>>1.
1605 if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
1606 // handle most cases here (ch is a BMP code point or a
1607 // negative value (invalid code point))
1608 final char[] value = this.toCharArray();
1609 final int offset = this.offset();
1610 final int max = offset + length();
1611 for (int i = offset + fromIndex; i < max ; i++) {
1612 if (value[i] == ch) {
1618 return indexOfSupplementary(ch, fromIndex);
1623 * Handles (rare) calls of indexOf with a supplementary character.
1625 private int indexOfSupplementary(int ch, int fromIndex) {
1626 if (Character.isValidCodePoint(ch)) {
1627 final char[] value = this.toCharArray();
1628 final int offset = this.offset();
1629 final char hi = Character.highSurrogate(ch);
1630 final char lo = Character.lowSurrogate(ch);
1631 final int max = offset + length() - 1;
1632 for (int i = offset + fromIndex; i < max; i++) {
1633 if (value[i] == hi && value[i+1] == lo) {
1642 * Returns the index within this string of the last occurrence of
1643 * the specified character. For values of <code>ch</code> in the
1644 * range from 0 to 0xFFFF (inclusive), the index (in Unicode code
1645 * units) returned is the largest value <i>k</i> such that:
1647 * this.charAt(<i>k</i>) == ch
1648 * </pre></blockquote>
1649 * is true. For other values of <code>ch</code>, it is the
1650 * largest value <i>k</i> such that:
1652 * this.codePointAt(<i>k</i>) == ch
1653 * </pre></blockquote>
1654 * is true. In either case, if no such character occurs in this
1655 * string, then <code>-1</code> is returned. The
1656 * <code>String</code> is searched backwards starting at the last
1659 * @param ch a character (Unicode code point).
1660 * @return the index of the last occurrence of the character in the
1661 * character sequence represented by this object, or
1662 * <code>-1</code> if the character does not occur.
1664 public int lastIndexOf(int ch) {
1665 return lastIndexOf(ch, length() - 1);
1669 * Returns the index within this string of the last occurrence of
1670 * the specified character, searching backward starting at the
1671 * specified index. For values of <code>ch</code> in the range
1672 * from 0 to 0xFFFF (inclusive), the index returned is the largest
1673 * value <i>k</i> such that:
1675 * (this.charAt(<i>k</i>) == ch) && (<i>k</i> <= fromIndex)
1676 * </pre></blockquote>
1677 * is true. For other values of <code>ch</code>, it is the
1678 * largest value <i>k</i> such that:
1680 * (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> <= fromIndex)
1681 * </pre></blockquote>
1682 * is true. In either case, if no such character occurs in this
1683 * string at or before position <code>fromIndex</code>, then
1684 * <code>-1</code> is returned.
1686 * <p>All indices are specified in <code>char</code> values
1687 * (Unicode code units).
1689 * @param ch a character (Unicode code point).
1690 * @param fromIndex the index to start the search from. There is no
1691 * restriction on the value of <code>fromIndex</code>. If it is
1692 * greater than or equal to the length of this string, it has
1693 * the same effect as if it were equal to one less than the
1694 * length of this string: this entire string may be searched.
1695 * If it is negative, it has the same effect as if it were -1:
1697 * @return the index of the last occurrence of the character in the
1698 * character sequence represented by this object that is less
1699 * than or equal to <code>fromIndex</code>, or <code>-1</code>
1700 * if the character does not occur before that point.
1702 @JavaScriptBody(args = { "ch", "from" }, body =
1703 "if (typeof ch === 'number') ch = String.fromCharCode(ch);\n" +
1704 "return this.toString().lastIndexOf(ch, from);"
1706 public int lastIndexOf(int ch, int fromIndex) {
1707 if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
1708 // handle most cases here (ch is a BMP code point or a
1709 // negative value (invalid code point))
1710 final char[] value = this.toCharArray();
1711 final int offset = this.offset();
1712 int i = offset + Math.min(fromIndex, length() - 1);
1713 for (; i >= offset ; i--) {
1714 if (value[i] == ch) {
1720 return lastIndexOfSupplementary(ch, fromIndex);
1725 * Handles (rare) calls of lastIndexOf with a supplementary character.
1727 private int lastIndexOfSupplementary(int ch, int fromIndex) {
1728 if (Character.isValidCodePoint(ch)) {
1729 final char[] value = this.toCharArray();
1730 final int offset = this.offset();
1731 char hi = Character.highSurrogate(ch);
1732 char lo = Character.lowSurrogate(ch);
1733 int i = offset + Math.min(fromIndex, length() - 2);
1734 for (; i >= offset; i--) {
1735 if (value[i] == hi && value[i+1] == lo) {
1744 * Returns the index within this string of the first occurrence of the
1745 * specified substring.
1747 * <p>The returned index is the smallest value <i>k</i> for which:
1749 * this.startsWith(str, <i>k</i>)
1750 * </pre></blockquote>
1751 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1753 * @param str the substring to search for.
1754 * @return the index of the first occurrence of the specified substring,
1755 * or {@code -1} if there is no such occurrence.
1757 public int indexOf(String str) {
1758 return indexOf(str, 0);
1762 * Returns the index within this string of the first occurrence of the
1763 * specified substring, starting at the specified index.
1765 * <p>The returned index is the smallest value <i>k</i> for which:
1767 * <i>k</i> >= fromIndex && this.startsWith(str, <i>k</i>)
1768 * </pre></blockquote>
1769 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1771 * @param str the substring to search for.
1772 * @param fromIndex the index from which to start the search.
1773 * @return the index of the first occurrence of the specified substring,
1774 * starting at the specified index,
1775 * or {@code -1} if there is no such occurrence.
1777 @JavaScriptBody(args = { "str", "fromIndex" }, body =
1778 "return this.toString().indexOf(str.toString(), fromIndex);"
1780 public native int indexOf(String str, int fromIndex);
1783 * Returns the index within this string of the last occurrence of the
1784 * specified substring. The last occurrence of the empty string ""
1785 * is considered to occur at the index value {@code this.length()}.
1787 * <p>The returned index is the largest value <i>k</i> for which:
1789 * this.startsWith(str, <i>k</i>)
1790 * </pre></blockquote>
1791 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1793 * @param str the substring to search for.
1794 * @return the index of the last occurrence of the specified substring,
1795 * or {@code -1} if there is no such occurrence.
1797 public int lastIndexOf(String str) {
1798 return lastIndexOf(str, length());
1802 * Returns the index within this string of the last occurrence of the
1803 * specified substring, searching backward starting at the specified index.
1805 * <p>The returned index is the largest value <i>k</i> for which:
1807 * <i>k</i> <= fromIndex && this.startsWith(str, <i>k</i>)
1808 * </pre></blockquote>
1809 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1811 * @param str the substring to search for.
1812 * @param fromIndex the index to start the search from.
1813 * @return the index of the last occurrence of the specified substring,
1814 * searching backward from the specified index,
1815 * or {@code -1} if there is no such occurrence.
1817 @JavaScriptBody(args = { "s", "from" }, body =
1818 "return this.toString().lastIndexOf(s.toString(), from);"
1820 public int lastIndexOf(String str, int fromIndex) {
1821 return lastIndexOf(toCharArray(), offset(), length(), str.toCharArray(), str.offset(), str.length(), fromIndex);
1825 * Code shared by String and StringBuffer to do searches. The
1826 * source is the character array being searched, and the target
1827 * is the string being searched for.
1829 * @param source the characters being searched.
1830 * @param sourceOffset offset of the source string.
1831 * @param sourceCount count of the source string.
1832 * @param target the characters being searched for.
1833 * @param targetOffset offset of the target string.
1834 * @param targetCount count of the target string.
1835 * @param fromIndex the index to begin searching from.
1837 static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
1838 char[] target, int targetOffset, int targetCount,
1841 * Check arguments; return immediately where possible. For
1842 * consistency, don't check for null str.
1844 int rightIndex = sourceCount - targetCount;
1845 if (fromIndex < 0) {
1848 if (fromIndex > rightIndex) {
1849 fromIndex = rightIndex;
1851 /* Empty string always matches. */
1852 if (targetCount == 0) {
1856 int strLastIndex = targetOffset + targetCount - 1;
1857 char strLastChar = target[strLastIndex];
1858 int min = sourceOffset + targetCount - 1;
1859 int i = min + fromIndex;
1861 startSearchForLastChar:
1863 while (i >= min && source[i] != strLastChar) {
1870 int start = j - (targetCount - 1);
1871 int k = strLastIndex - 1;
1874 if (source[j--] != target[k--]) {
1876 continue startSearchForLastChar;
1879 return start - sourceOffset + 1;
1884 * Returns a new string that is a substring of this string. The
1885 * substring begins with the character at the specified index and
1886 * extends to the end of this string. <p>
1889 * "unhappy".substring(2) returns "happy"
1890 * "Harbison".substring(3) returns "bison"
1891 * "emptiness".substring(9) returns "" (an empty string)
1892 * </pre></blockquote>
1894 * @param beginIndex the beginning index, inclusive.
1895 * @return the specified substring.
1896 * @exception IndexOutOfBoundsException if
1897 * <code>beginIndex</code> is negative or larger than the
1898 * length of this <code>String</code> object.
1900 public String substring(int beginIndex) {
1901 return substring(beginIndex, length());
1905 * Returns a new string that is a substring of this string. The
1906 * substring begins at the specified <code>beginIndex</code> and
1907 * extends to the character at index <code>endIndex - 1</code>.
1908 * Thus the length of the substring is <code>endIndex-beginIndex</code>.
1912 * "hamburger".substring(4, 8) returns "urge"
1913 * "smiles".substring(1, 5) returns "mile"
1914 * </pre></blockquote>
1916 * @param beginIndex the beginning index, inclusive.
1917 * @param endIndex the ending index, exclusive.
1918 * @return the specified substring.
1919 * @exception IndexOutOfBoundsException if the
1920 * <code>beginIndex</code> is negative, or
1921 * <code>endIndex</code> is larger than the length of
1922 * this <code>String</code> object, or
1923 * <code>beginIndex</code> is larger than
1924 * <code>endIndex</code>.
1926 @JavaScriptBody(args = { "beginIndex", "endIndex" }, body =
1927 "return this.toString().substring(beginIndex, endIndex);"
1929 public String substring(int beginIndex, int endIndex) {
1930 if (beginIndex < 0) {
1931 throw new StringIndexOutOfBoundsException(beginIndex);
1933 if (endIndex > length()) {
1934 throw new StringIndexOutOfBoundsException(endIndex);
1936 if (beginIndex > endIndex) {
1937 throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
1939 return ((beginIndex == 0) && (endIndex == length())) ? this :
1940 new String(toCharArray(), offset() + beginIndex, endIndex - beginIndex);
1944 * Returns a new character sequence that is a subsequence of this sequence.
1946 * <p> An invocation of this method of the form
1949 * str.subSequence(begin, end)</pre></blockquote>
1951 * behaves in exactly the same way as the invocation
1954 * str.substring(begin, end)</pre></blockquote>
1956 * This method is defined so that the <tt>String</tt> class can implement
1957 * the {@link CharSequence} interface. </p>
1959 * @param beginIndex the begin index, inclusive.
1960 * @param endIndex the end index, exclusive.
1961 * @return the specified subsequence.
1963 * @throws IndexOutOfBoundsException
1964 * if <tt>beginIndex</tt> or <tt>endIndex</tt> are negative,
1965 * if <tt>endIndex</tt> is greater than <tt>length()</tt>,
1966 * or if <tt>beginIndex</tt> is greater than <tt>startIndex</tt>
1971 public CharSequence subSequence(int beginIndex, int endIndex) {
1972 return this.substring(beginIndex, endIndex);
1976 * Concatenates the specified string to the end of this string.
1978 * If the length of the argument string is <code>0</code>, then this
1979 * <code>String</code> object is returned. Otherwise, a new
1980 * <code>String</code> object is created, representing a character
1981 * sequence that is the concatenation of the character sequence
1982 * represented by this <code>String</code> object and the character
1983 * sequence represented by the argument string.<p>
1986 * "cares".concat("s") returns "caress"
1987 * "to".concat("get").concat("her") returns "together"
1988 * </pre></blockquote>
1990 * @param str the <code>String</code> that is concatenated to the end
1991 * of this <code>String</code>.
1992 * @return a string that represents the concatenation of this object's
1993 * characters followed by the string argument's characters.
1995 public String concat(String str) {
1996 int otherLen = str.length();
1997 if (otherLen == 0) {
2000 char buf[] = new char[length() + otherLen];
2001 getChars(0, length(), buf, 0);
2002 str.getChars(0, otherLen, buf, length());
2003 return new String(buf, 0, length() + otherLen);
2007 * Returns a new string resulting from replacing all occurrences of
2008 * <code>oldChar</code> in this string with <code>newChar</code>.
2010 * If the character <code>oldChar</code> does not occur in the
2011 * character sequence represented by this <code>String</code> object,
2012 * then a reference to this <code>String</code> object is returned.
2013 * Otherwise, a new <code>String</code> object is created that
2014 * represents a character sequence identical to the character sequence
2015 * represented by this <code>String</code> object, except that every
2016 * occurrence of <code>oldChar</code> is replaced by an occurrence
2017 * of <code>newChar</code>.
2021 * "mesquite in your cellar".replace('e', 'o')
2022 * returns "mosquito in your collar"
2023 * "the war of baronets".replace('r', 'y')
2024 * returns "the way of bayonets"
2025 * "sparring with a purple porpoise".replace('p', 't')
2026 * returns "starring with a turtle tortoise"
2027 * "JonL".replace('q', 'x') returns "JonL" (no change)
2028 * </pre></blockquote>
2030 * @param oldChar the old character.
2031 * @param newChar the new character.
2032 * @return a string derived from this string by replacing every
2033 * occurrence of <code>oldChar</code> with <code>newChar</code>.
2035 @JavaScriptBody(args = { "arg1", "arg2" }, body =
2036 "if (typeof arg1 === 'number') arg1 = String.fromCharCode(arg1);\n" +
2037 "if (typeof arg2 === 'number') arg2 = String.fromCharCode(arg2);\n" +
2038 "var s = this.toString();\n" +
2040 " var ret = s.replace(arg1, arg2);\n" +
2041 " if (ret === s) {\n" +
2047 public String replace(char oldChar, char newChar) {
2048 if (oldChar != newChar) {
2051 char[] val = toCharArray(); /* avoid getfield opcode */
2052 int off = offset(); /* avoid getfield opcode */
2055 if (val[off + i] == oldChar) {
2060 char buf[] = new char[len];
2061 for (int j = 0 ; j < i ; j++) {
2062 buf[j] = val[off+j];
2065 char c = val[off + i];
2066 buf[i] = (c == oldChar) ? newChar : c;
2069 return new String(buf, 0, len);
2076 * Tells whether or not this string matches the given <a
2077 * href="../util/regex/Pattern.html#sum">regular expression</a>.
2079 * <p> An invocation of this method of the form
2080 * <i>str</i><tt>.matches(</tt><i>regex</i><tt>)</tt> yields exactly the
2081 * same result as the expression
2083 * <blockquote><tt> {@link java.util.regex.Pattern}.{@link
2084 * java.util.regex.Pattern#matches(String,CharSequence)
2085 * matches}(</tt><i>regex</i><tt>,</tt> <i>str</i><tt>)</tt></blockquote>
2088 * the regular expression to which this string is to be matched
2090 * @return <tt>true</tt> if, and only if, this string matches the
2091 * given regular expression
2093 * @throws PatternSyntaxException
2094 * if the regular expression's syntax is invalid
2096 * @see java.util.regex.Pattern
2101 @JavaScriptBody(args = { "regex" }, body =
2102 "var self = this.toString();\n"
2103 + "var re = new RegExp(regex.toString());\n"
2104 + "var r = re.exec(self);\n"
2105 + "return r != null && r.length > 0 && self.length == r[0].length;"
2107 public boolean matches(String regex) {
2108 throw new UnsupportedOperationException();
2112 * Returns true if and only if this string contains the specified
2113 * sequence of char values.
2115 * @param s the sequence to search for
2116 * @return true if this string contains <code>s</code>, false otherwise
2117 * @throws NullPointerException if <code>s</code> is <code>null</code>
2120 public boolean contains(CharSequence s) {
2121 return indexOf(s.toString()) > -1;
2125 * Replaces the first substring of this string that matches the given <a
2126 * href="../util/regex/Pattern.html#sum">regular expression</a> with the
2127 * given replacement.
2129 * <p> An invocation of this method of the form
2130 * <i>str</i><tt>.replaceFirst(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt>
2131 * yields exactly the same result as the expression
2134 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2135 * compile}(</tt><i>regex</i><tt>).{@link
2136 * java.util.regex.Pattern#matcher(java.lang.CharSequence)
2137 * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceFirst
2138 * replaceFirst}(</tt><i>repl</i><tt>)</tt></blockquote>
2141 * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the
2142 * replacement string may cause the results to be different than if it were
2143 * being treated as a literal replacement string; see
2144 * {@link java.util.regex.Matcher#replaceFirst}.
2145 * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
2146 * meaning of these characters, if desired.
2149 * the regular expression to which this string is to be matched
2150 * @param replacement
2151 * the string to be substituted for the first match
2153 * @return The resulting <tt>String</tt>
2155 * @throws PatternSyntaxException
2156 * if the regular expression's syntax is invalid
2158 * @see java.util.regex.Pattern
2163 @JavaScriptBody(args = { "regex", "newText" }, body =
2164 "var self = this.toString();\n"
2165 + "var re = new RegExp(regex.toString());\n"
2166 + "var r = re.exec(self);\n"
2167 + "if (r === null || r.length === 0) return this;\n"
2168 + "var from = self.indexOf(r[0]);\n"
2169 + "return this.substring(0, from) + newText + this.substring(from + r[0].length);\n"
2171 public String replaceFirst(String regex, String replacement) {
2172 throw new UnsupportedOperationException();
2176 * Replaces each substring of this string that matches the given <a
2177 * href="../util/regex/Pattern.html#sum">regular expression</a> with the
2178 * given replacement.
2180 * <p> An invocation of this method of the form
2181 * <i>str</i><tt>.replaceAll(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt>
2182 * yields exactly the same result as the expression
2185 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2186 * compile}(</tt><i>regex</i><tt>).{@link
2187 * java.util.regex.Pattern#matcher(java.lang.CharSequence)
2188 * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceAll
2189 * replaceAll}(</tt><i>repl</i><tt>)</tt></blockquote>
2192 * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the
2193 * replacement string may cause the results to be different than if it were
2194 * being treated as a literal replacement string; see
2195 * {@link java.util.regex.Matcher#replaceAll Matcher.replaceAll}.
2196 * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
2197 * meaning of these characters, if desired.
2200 * the regular expression to which this string is to be matched
2201 * @param replacement
2202 * the string to be substituted for each match
2204 * @return The resulting <tt>String</tt>
2206 * @throws PatternSyntaxException
2207 * if the regular expression's syntax is invalid
2209 * @see java.util.regex.Pattern
2214 public String replaceAll(String regex, String replacement) {
2217 String n = p.replaceFirst(regex, replacement);
2226 * Replaces each substring of this string that matches the literal target
2227 * sequence with the specified literal replacement sequence. The
2228 * replacement proceeds from the beginning of the string to the end, for
2229 * example, replacing "aa" with "b" in the string "aaa" will result in
2230 * "ba" rather than "ab".
2232 * @param target The sequence of char values to be replaced
2233 * @param replacement The replacement sequence of char values
2234 * @return The resulting string
2235 * @throws NullPointerException if <code>target</code> or
2236 * <code>replacement</code> is <code>null</code>.
2239 @JavaScriptBody(args = { "target", "replacement" }, body =
2240 "var s = this.toString();\n"
2241 + "target = target.toString();\n"
2242 + "replacement = replacement.toString();\n"
2245 + " var indx = s.indexOf(target, pos);\n"
2246 + " if (indx === -1) {\n"
2249 + " pos = indx + replacement.length;\n"
2250 + " s = s.substring(0, indx) + replacement + s.substring(indx + target.length);\n"
2253 public native String replace(CharSequence target, CharSequence replacement);
2256 * Splits this string around matches of the given
2257 * <a href="../util/regex/Pattern.html#sum">regular expression</a>.
2259 * <p> The array returned by this method contains each substring of this
2260 * string that is terminated by another substring that matches the given
2261 * expression or is terminated by the end of the string. The substrings in
2262 * the array are in the order in which they occur in this string. If the
2263 * expression does not match any part of the input then the resulting array
2264 * has just one element, namely this string.
2266 * <p> The <tt>limit</tt> parameter controls the number of times the
2267 * pattern is applied and therefore affects the length of the resulting
2268 * array. If the limit <i>n</i> is greater than zero then the pattern
2269 * will be applied at most <i>n</i> - 1 times, the array's
2270 * length will be no greater than <i>n</i>, and the array's last entry
2271 * will contain all input beyond the last matched delimiter. If <i>n</i>
2272 * is non-positive then the pattern will be applied as many times as
2273 * possible and the array can have any length. If <i>n</i> is zero then
2274 * the pattern will be applied as many times as possible, the array can
2275 * have any length, and trailing empty strings will be discarded.
2277 * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the
2278 * following results with these parameters:
2280 * <blockquote><table cellpadding=1 cellspacing=0 summary="Split example showing regex, limit, and result">
2286 * <tr><td align=center>:</td>
2287 * <td align=center>2</td>
2288 * <td><tt>{ "boo", "and:foo" }</tt></td></tr>
2289 * <tr><td align=center>:</td>
2290 * <td align=center>5</td>
2291 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2292 * <tr><td align=center>:</td>
2293 * <td align=center>-2</td>
2294 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2295 * <tr><td align=center>o</td>
2296 * <td align=center>5</td>
2297 * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
2298 * <tr><td align=center>o</td>
2299 * <td align=center>-2</td>
2300 * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
2301 * <tr><td align=center>o</td>
2302 * <td align=center>0</td>
2303 * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
2304 * </table></blockquote>
2306 * <p> An invocation of this method of the form
2307 * <i>str.</i><tt>split(</tt><i>regex</i><tt>,</tt> <i>n</i><tt>)</tt>
2308 * yields the same result as the expression
2311 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2312 * compile}<tt>(</tt><i>regex</i><tt>)</tt>.{@link
2313 * java.util.regex.Pattern#split(java.lang.CharSequence,int)
2314 * split}<tt>(</tt><i>str</i><tt>,</tt> <i>n</i><tt>)</tt>
2319 * the delimiting regular expression
2322 * the result threshold, as described above
2324 * @return the array of strings computed by splitting this string
2325 * around matches of the given regular expression
2327 * @throws PatternSyntaxException
2328 * if the regular expression's syntax is invalid
2330 * @see java.util.regex.Pattern
2335 public String[] split(String regex, int limit) {
2337 Object[] arr = splitImpl(this, regex, Integer.MAX_VALUE);
2338 int to = arr.length;
2340 while (to > 1 && ((String)arr[--to]).isEmpty()) {
2344 String[] ret = new String[to];
2345 System.arraycopy(arr, 0, ret, 0, to);
2348 Object[] arr = splitImpl(this, regex, limit);
2349 String[] ret = new String[arr.length];
2351 for (int i = 0; i < arr.length; i++) {
2352 final String s = (String)arr[i];
2354 pos = indexOf(s, pos) + s.length();
2356 ret[arr.length - 1] += substring(pos);
2361 @JavaScriptBody(args = { "str", "regex", "limit"}, body =
2362 "return str.split(new RegExp(regex), limit);"
2364 private static native Object[] splitImpl(String str, String regex, int limit);
2367 * Splits this string around matches of the given <a
2368 * href="../util/regex/Pattern.html#sum">regular expression</a>.
2370 * <p> This method works as if by invoking the two-argument {@link
2371 * #split(String, int) split} method with the given expression and a limit
2372 * argument of zero. Trailing empty strings are therefore not included in
2373 * the resulting array.
2375 * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the following
2376 * results with these expressions:
2378 * <blockquote><table cellpadding=1 cellspacing=0 summary="Split examples showing regex and result">
2383 * <tr><td align=center>:</td>
2384 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2385 * <tr><td align=center>o</td>
2386 * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
2387 * </table></blockquote>
2391 * the delimiting regular expression
2393 * @return the array of strings computed by splitting this string
2394 * around matches of the given regular expression
2396 * @throws PatternSyntaxException
2397 * if the regular expression's syntax is invalid
2399 * @see java.util.regex.Pattern
2404 public String[] split(String regex) {
2405 return split(regex, 0);
2409 * Converts all of the characters in this <code>String</code> to lower
2410 * case using the rules of the given <code>Locale</code>. Case mapping is based
2411 * on the Unicode Standard version specified by the {@link java.lang.Character Character}
2412 * class. Since case mappings are not always 1:1 char mappings, the resulting
2413 * <code>String</code> may be a different length than the original <code>String</code>.
2415 * Examples of lowercase mappings are in the following table:
2416 * <table border="1" summary="Lowercase mapping examples showing language code of locale, upper case, lower case, and description">
2418 * <th>Language Code of Locale</th>
2419 * <th>Upper Case</th>
2420 * <th>Lower Case</th>
2421 * <th>Description</th>
2424 * <td>tr (Turkish)</td>
2425 * <td>\u0130</td>
2426 * <td>\u0069</td>
2427 * <td>capital letter I with dot above -> small letter i</td>
2430 * <td>tr (Turkish)</td>
2431 * <td>\u0049</td>
2432 * <td>\u0131</td>
2433 * <td>capital letter I -> small letter dotless i </td>
2437 * <td>French Fries</td>
2438 * <td>french fries</td>
2439 * <td>lowercased all chars in String</td>
2443 * <td><img src="doc-files/capiota.gif" alt="capiota"><img src="doc-files/capchi.gif" alt="capchi">
2444 * <img src="doc-files/captheta.gif" alt="captheta"><img src="doc-files/capupsil.gif" alt="capupsil">
2445 * <img src="doc-files/capsigma.gif" alt="capsigma"></td>
2446 * <td><img src="doc-files/iota.gif" alt="iota"><img src="doc-files/chi.gif" alt="chi">
2447 * <img src="doc-files/theta.gif" alt="theta"><img src="doc-files/upsilon.gif" alt="upsilon">
2448 * <img src="doc-files/sigma1.gif" alt="sigma"></td>
2449 * <td>lowercased all chars in String</td>
2453 * @param locale use the case transformation rules for this locale
2454 * @return the <code>String</code>, converted to lowercase.
2455 * @see java.lang.String#toLowerCase()
2456 * @see java.lang.String#toUpperCase()
2457 * @see java.lang.String#toUpperCase(Locale)
2460 public String toLowerCase(java.util.Locale locale) {
2461 return toLowerCase();
2463 // if (locale == null) {
2464 // throw new NullPointerException();
2469 // /* Now check if there are any characters that need to be changed. */
2471 // for (firstUpper = 0 ; firstUpper < count; ) {
2472 // char c = value[offset+firstUpper];
2473 // if ((c >= Character.MIN_HIGH_SURROGATE) &&
2474 // (c <= Character.MAX_HIGH_SURROGATE)) {
2475 // int supplChar = codePointAt(firstUpper);
2476 // if (supplChar != Character.toLowerCase(supplChar)) {
2479 // firstUpper += Character.charCount(supplChar);
2481 // if (c != Character.toLowerCase(c)) {
2490 // char[] result = new char[count];
2491 // int resultOffset = 0; /* result may grow, so i+resultOffset
2492 // * is the write location in result */
2494 // /* Just copy the first few lowerCase characters. */
2495 // System.arraycopy(value, offset, result, 0, firstUpper);
2497 // String lang = locale.getLanguage();
2498 // boolean localeDependent =
2499 // (lang == "tr" || lang == "az" || lang == "lt");
2500 // char[] lowerCharArray;
2504 // for (int i = firstUpper; i < count; i += srcCount) {
2505 // srcChar = (int)value[offset+i];
2506 // if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
2507 // (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
2508 // srcChar = codePointAt(i);
2509 // srcCount = Character.charCount(srcChar);
2513 // if (localeDependent || srcChar == '\u03A3') { // GREEK CAPITAL LETTER SIGMA
2514 // lowerChar = ConditionalSpecialCasing.toLowerCaseEx(this, i, locale);
2515 // } else if (srcChar == '\u0130') { // LATIN CAPITAL LETTER I DOT
2516 // lowerChar = Character.ERROR;
2518 // lowerChar = Character.toLowerCase(srcChar);
2520 // if ((lowerChar == Character.ERROR) ||
2521 // (lowerChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
2522 // if (lowerChar == Character.ERROR) {
2523 // if (!localeDependent && srcChar == '\u0130') {
2525 // ConditionalSpecialCasing.toLowerCaseCharArray(this, i, Locale.ENGLISH);
2528 // ConditionalSpecialCasing.toLowerCaseCharArray(this, i, locale);
2530 // } else if (srcCount == 2) {
2531 // resultOffset += Character.toChars(lowerChar, result, i + resultOffset) - srcCount;
2534 // lowerCharArray = Character.toChars(lowerChar);
2537 // /* Grow result if needed */
2538 // int mapLen = lowerCharArray.length;
2539 // if (mapLen > srcCount) {
2540 // char[] result2 = new char[result.length + mapLen - srcCount];
2541 // System.arraycopy(result, 0, result2, 0,
2542 // i + resultOffset);
2543 // result = result2;
2545 // for (int x=0; x<mapLen; ++x) {
2546 // result[i+resultOffset+x] = lowerCharArray[x];
2548 // resultOffset += (mapLen - srcCount);
2550 // result[i+resultOffset] = (char)lowerChar;
2553 // return new String(0, count+resultOffset, result);
2557 * Converts all of the characters in this <code>String</code> to lower
2558 * case using the rules of the default locale. This is equivalent to calling
2559 * <code>toLowerCase(Locale.getDefault())</code>.
2561 * <b>Note:</b> This method is locale sensitive, and may produce unexpected
2562 * results if used for strings that are intended to be interpreted locale
2564 * Examples are programming language identifiers, protocol keys, and HTML
2566 * For instance, <code>"TITLE".toLowerCase()</code> in a Turkish locale
2567 * returns <code>"t\u005Cu0131tle"</code>, where '\u005Cu0131' is the
2568 * LATIN SMALL LETTER DOTLESS I character.
2569 * To obtain correct results for locale insensitive strings, use
2570 * <code>toLowerCase(Locale.ENGLISH)</code>.
2572 * @return the <code>String</code>, converted to lowercase.
2573 * @see java.lang.String#toLowerCase(Locale)
2575 @JavaScriptBody(args = {}, body = "return this.toLowerCase();")
2576 public String toLowerCase() {
2581 * Converts all of the characters in this <code>String</code> to upper
2582 * case using the rules of the given <code>Locale</code>. Case mapping is based
2583 * on the Unicode Standard version specified by the {@link java.lang.Character Character}
2584 * class. Since case mappings are not always 1:1 char mappings, the resulting
2585 * <code>String</code> may be a different length than the original <code>String</code>.
2587 * Examples of locale-sensitive and 1:M case mappings are in the following table.
2589 * <table border="1" summary="Examples of locale-sensitive and 1:M case mappings. Shows Language code of locale, lower case, upper case, and description.">
2591 * <th>Language Code of Locale</th>
2592 * <th>Lower Case</th>
2593 * <th>Upper Case</th>
2594 * <th>Description</th>
2597 * <td>tr (Turkish)</td>
2598 * <td>\u0069</td>
2599 * <td>\u0130</td>
2600 * <td>small letter i -> capital letter I with dot above</td>
2603 * <td>tr (Turkish)</td>
2604 * <td>\u0131</td>
2605 * <td>\u0049</td>
2606 * <td>small letter dotless i -> capital letter I</td>
2610 * <td>\u00df</td>
2611 * <td>\u0053 \u0053</td>
2612 * <td>small letter sharp s -> two letters: SS</td>
2616 * <td>Fahrvergnügen</td>
2617 * <td>FAHRVERGNÜGEN</td>
2621 * @param locale use the case transformation rules for this locale
2622 * @return the <code>String</code>, converted to uppercase.
2623 * @see java.lang.String#toUpperCase()
2624 * @see java.lang.String#toLowerCase()
2625 * @see java.lang.String#toLowerCase(Locale)
2628 public String toUpperCase(Locale locale) {
2629 return toUpperCase();
2631 /* not for javascript
2632 if (locale == null) {
2633 throw new NullPointerException();
2638 // Now check if there are any characters that need to be changed.
2640 for (firstLower = 0 ; firstLower < count; ) {
2641 int c = (int)value[offset+firstLower];
2643 if ((c >= Character.MIN_HIGH_SURROGATE) &&
2644 (c <= Character.MAX_HIGH_SURROGATE)) {
2645 c = codePointAt(firstLower);
2646 srcCount = Character.charCount(c);
2650 int upperCaseChar = Character.toUpperCaseEx(c);
2651 if ((upperCaseChar == Character.ERROR) ||
2652 (c != upperCaseChar)) {
2655 firstLower += srcCount;
2660 char[] result = new char[count]; /* may grow *
2661 int resultOffset = 0; /* result may grow, so i+resultOffset
2662 * is the write location in result *
2664 /* Just copy the first few upperCase characters. *
2665 System.arraycopy(value, offset, result, 0, firstLower);
2667 String lang = locale.getLanguage();
2668 boolean localeDependent =
2669 (lang == "tr" || lang == "az" || lang == "lt");
2670 char[] upperCharArray;
2674 for (int i = firstLower; i < count; i += srcCount) {
2675 srcChar = (int)value[offset+i];
2676 if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
2677 (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
2678 srcChar = codePointAt(i);
2679 srcCount = Character.charCount(srcChar);
2683 if (localeDependent) {
2684 upperChar = ConditionalSpecialCasing.toUpperCaseEx(this, i, locale);
2686 upperChar = Character.toUpperCaseEx(srcChar);
2688 if ((upperChar == Character.ERROR) ||
2689 (upperChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
2690 if (upperChar == Character.ERROR) {
2691 if (localeDependent) {
2693 ConditionalSpecialCasing.toUpperCaseCharArray(this, i, locale);
2695 upperCharArray = Character.toUpperCaseCharArray(srcChar);
2697 } else if (srcCount == 2) {
2698 resultOffset += Character.toChars(upperChar, result, i + resultOffset) - srcCount;
2701 upperCharArray = Character.toChars(upperChar);
2704 /* Grow result if needed *
2705 int mapLen = upperCharArray.length;
2706 if (mapLen > srcCount) {
2707 char[] result2 = new char[result.length + mapLen - srcCount];
2708 System.arraycopy(result, 0, result2, 0,
2712 for (int x=0; x<mapLen; ++x) {
2713 result[i+resultOffset+x] = upperCharArray[x];
2715 resultOffset += (mapLen - srcCount);
2717 result[i+resultOffset] = (char)upperChar;
2720 return new String(0, count+resultOffset, result);
2725 * Converts all of the characters in this <code>String</code> to upper
2726 * case using the rules of the default locale. This method is equivalent to
2727 * <code>toUpperCase(Locale.getDefault())</code>.
2729 * <b>Note:</b> This method is locale sensitive, and may produce unexpected
2730 * results if used for strings that are intended to be interpreted locale
2732 * Examples are programming language identifiers, protocol keys, and HTML
2734 * For instance, <code>"title".toUpperCase()</code> in a Turkish locale
2735 * returns <code>"T\u005Cu0130TLE"</code>, where '\u005Cu0130' is the
2736 * LATIN CAPITAL LETTER I WITH DOT ABOVE character.
2737 * To obtain correct results for locale insensitive strings, use
2738 * <code>toUpperCase(Locale.ENGLISH)</code>.
2740 * @return the <code>String</code>, converted to uppercase.
2741 * @see java.lang.String#toUpperCase(Locale)
2743 @JavaScriptBody(args = {}, body = "return this.toUpperCase();")
2744 public String toUpperCase() {
2749 * Returns a copy of the string, with leading and trailing whitespace
2752 * If this <code>String</code> object represents an empty character
2753 * sequence, or the first and last characters of character sequence
2754 * represented by this <code>String</code> object both have codes
2755 * greater than <code>'\u0020'</code> (the space character), then a
2756 * reference to this <code>String</code> object is returned.
2758 * Otherwise, if there is no character with a code greater than
2759 * <code>'\u0020'</code> in the string, then a new
2760 * <code>String</code> object representing an empty string is created
2763 * Otherwise, let <i>k</i> be the index of the first character in the
2764 * string whose code is greater than <code>'\u0020'</code>, and let
2765 * <i>m</i> be the index of the last character in the string whose code
2766 * is greater than <code>'\u0020'</code>. A new <code>String</code>
2767 * object is created, representing the substring of this string that
2768 * begins with the character at index <i>k</i> and ends with the
2769 * character at index <i>m</i>-that is, the result of
2770 * <code>this.substring(<i>k</i>, <i>m</i>+1)</code>.
2772 * This method may be used to trim whitespace (as defined above) from
2773 * the beginning and end of a string.
2775 * @return A copy of this string with leading and trailing white
2776 * space removed, or this string if it has no leading or
2777 * trailing white space.
2779 public String trim() {
2782 int off = offset(); /* avoid getfield opcode */
2783 char[] val = toCharArray(); /* avoid getfield opcode */
2785 while ((st < len) && (val[off + st] <= ' ')) {
2788 while ((st < len) && (val[off + len - 1] <= ' ')) {
2791 return ((st > 0) || (len < length())) ? substring(st, len) : this;
2795 * This object (which is already a string!) is itself returned.
2797 * @return the string itself.
2799 @JavaScriptBody(args = {}, body = "return this.toString();")
2800 public String toString() {
2805 * Converts this string to a new character array.
2807 * @return a newly allocated character array whose length is the length
2808 * of this string and whose contents are initialized to contain
2809 * the character sequence represented by this string.
2811 public char[] toCharArray() {
2812 char result[] = new char[length()];
2813 getChars(0, length(), result, 0);
2818 * Returns a formatted string using the specified format string and
2821 * <p> The locale always used is the one returned by {@link
2822 * java.util.Locale#getDefault() Locale.getDefault()}.
2825 * A <a href="../util/Formatter.html#syntax">format string</a>
2828 * Arguments referenced by the format specifiers in the format
2829 * string. If there are more arguments than format specifiers, the
2830 * extra arguments are ignored. The number of arguments is
2831 * variable and may be zero. The maximum number of arguments is
2832 * limited by the maximum dimension of a Java array as defined by
2833 * <cite>The Java™ Virtual Machine Specification</cite>.
2834 * The behaviour on a
2835 * <tt>null</tt> argument depends on the <a
2836 * href="../util/Formatter.html#syntax">conversion</a>.
2838 * @throws IllegalFormatException
2839 * If a format string contains an illegal syntax, a format
2840 * specifier that is incompatible with the given arguments,
2841 * insufficient arguments given the format string, or other
2842 * illegal conditions. For specification of all possible
2843 * formatting errors, see the <a
2844 * href="../util/Formatter.html#detail">Details</a> section of the
2845 * formatter class specification.
2847 * @throws NullPointerException
2848 * If the <tt>format</tt> is <tt>null</tt>
2850 * @return A formatted string
2852 * @see java.util.Formatter
2855 public static String format(String format, Object ... args) {
2856 return format((Locale)null, format, args);
2860 * Returns a formatted string using the specified locale, format string,
2864 * The {@linkplain java.util.Locale locale} to apply during
2865 * formatting. If <tt>l</tt> is <tt>null</tt> then no localization
2869 * A <a href="../util/Formatter.html#syntax">format string</a>
2872 * Arguments referenced by the format specifiers in the format
2873 * string. If there are more arguments than format specifiers, the
2874 * extra arguments are ignored. The number of arguments is
2875 * variable and may be zero. The maximum number of arguments is
2876 * limited by the maximum dimension of a Java array as defined by
2877 * <cite>The Java™ Virtual Machine Specification</cite>.
2878 * The behaviour on a
2879 * <tt>null</tt> argument depends on the <a
2880 * href="../util/Formatter.html#syntax">conversion</a>.
2882 * @throws IllegalFormatException
2883 * If a format string contains an illegal syntax, a format
2884 * specifier that is incompatible with the given arguments,
2885 * insufficient arguments given the format string, or other
2886 * illegal conditions. For specification of all possible
2887 * formatting errors, see the <a
2888 * href="../util/Formatter.html#detail">Details</a> section of the
2889 * formatter class specification
2891 * @throws NullPointerException
2892 * If the <tt>format</tt> is <tt>null</tt>
2894 * @return A formatted string
2896 * @see java.util.Formatter
2899 public static String format(Locale l, String format, Object ... args) {
2901 for (int i = 0; i < args.length; i++) {
2902 String v = args[i] == null ? "null" : args[i].toString();
2903 p = p.replaceFirst("%s", v);
2906 // return new Formatter(l).format(format, args).toString();
2910 * Returns the string representation of the <code>Object</code> argument.
2912 * @param obj an <code>Object</code>.
2913 * @return if the argument is <code>null</code>, then a string equal to
2914 * <code>"null"</code>; otherwise, the value of
2915 * <code>obj.toString()</code> is returned.
2916 * @see java.lang.Object#toString()
2918 public static String valueOf(Object obj) {
2919 return (obj == null) ? "null" : obj.toString();
2923 * Returns the string representation of the <code>char</code> array
2924 * argument. The contents of the character array are copied; subsequent
2925 * modification of the character array does not affect the newly
2928 * @param data a <code>char</code> array.
2929 * @return a newly allocated string representing the same sequence of
2930 * characters contained in the character array argument.
2932 public static String valueOf(char data[]) {
2933 return new String(data);
2937 * Returns the string representation of a specific subarray of the
2938 * <code>char</code> array argument.
2940 * The <code>offset</code> argument is the index of the first
2941 * character of the subarray. The <code>count</code> argument
2942 * specifies the length of the subarray. The contents of the subarray
2943 * are copied; subsequent modification of the character array does not
2944 * affect the newly created string.
2946 * @param data the character array.
2947 * @param offset the initial offset into the value of the
2948 * <code>String</code>.
2949 * @param count the length of the value of the <code>String</code>.
2950 * @return a string representing the sequence of characters contained
2951 * in the subarray of the character array argument.
2952 * @exception IndexOutOfBoundsException if <code>offset</code> is
2953 * negative, or <code>count</code> is negative, or
2954 * <code>offset+count</code> is larger than
2955 * <code>data.length</code>.
2957 public static String valueOf(char data[], int offset, int count) {
2958 return new String(data, offset, count);
2962 * Returns a String that represents the character sequence in the
2965 * @param data the character array.
2966 * @param offset initial offset of the subarray.
2967 * @param count length of the subarray.
2968 * @return a <code>String</code> that contains the characters of the
2969 * specified subarray of the character array.
2971 public static String copyValueOf(char data[], int offset, int count) {
2972 // All public String constructors now copy the data.
2973 return new String(data, offset, count);
2977 * Returns a String that represents the character sequence in the
2980 * @param data the character array.
2981 * @return a <code>String</code> that contains the characters of the
2984 public static String copyValueOf(char data[]) {
2985 return copyValueOf(data, 0, data.length);
2989 * Returns the string representation of the <code>boolean</code> argument.
2991 * @param b a <code>boolean</code>.
2992 * @return if the argument is <code>true</code>, a string equal to
2993 * <code>"true"</code> is returned; otherwise, a string equal to
2994 * <code>"false"</code> is returned.
2996 public static String valueOf(boolean b) {
2997 return b ? "true" : "false";
3001 * Returns the string representation of the <code>char</code>
3004 * @param c a <code>char</code>.
3005 * @return a string of length <code>1</code> containing
3006 * as its single character the argument <code>c</code>.
3008 public static String valueOf(char c) {
3010 return new String(data, 0, 1);
3014 * Returns the string representation of the <code>int</code> argument.
3016 * The representation is exactly the one returned by the
3017 * <code>Integer.toString</code> method of one argument.
3019 * @param i an <code>int</code>.
3020 * @return a string representation of the <code>int</code> argument.
3021 * @see java.lang.Integer#toString(int, int)
3023 public static String valueOf(int i) {
3024 return Integer.toString(i);
3028 * Returns the string representation of the <code>long</code> argument.
3030 * The representation is exactly the one returned by the
3031 * <code>Long.toString</code> method of one argument.
3033 * @param l a <code>long</code>.
3034 * @return a string representation of the <code>long</code> argument.
3035 * @see java.lang.Long#toString(long)
3037 public static String valueOf(long l) {
3038 return Long.toString(l);
3042 * Returns the string representation of the <code>float</code> argument.
3044 * The representation is exactly the one returned by the
3045 * <code>Float.toString</code> method of one argument.
3047 * @param f a <code>float</code>.
3048 * @return a string representation of the <code>float</code> argument.
3049 * @see java.lang.Float#toString(float)
3051 public static String valueOf(float f) {
3052 return Float.toString(f);
3056 * Returns the string representation of the <code>double</code> argument.
3058 * The representation is exactly the one returned by the
3059 * <code>Double.toString</code> method of one argument.
3061 * @param d a <code>double</code>.
3062 * @return a string representation of the <code>double</code> argument.
3063 * @see java.lang.Double#toString(double)
3065 public static String valueOf(double d) {
3066 return Double.toString(d);
3070 * Returns a canonical representation for the string object.
3072 * A pool of strings, initially empty, is maintained privately by the
3073 * class <code>String</code>.
3075 * When the intern method is invoked, if the pool already contains a
3076 * string equal to this <code>String</code> object as determined by
3077 * the {@link #equals(Object)} method, then the string from the pool is
3078 * returned. Otherwise, this <code>String</code> object is added to the
3079 * pool and a reference to this <code>String</code> object is returned.
3081 * It follows that for any two strings <code>s</code> and <code>t</code>,
3082 * <code>s.intern() == t.intern()</code> is <code>true</code>
3083 * if and only if <code>s.equals(t)</code> is <code>true</code>.
3085 * All literal strings and string-valued constant expressions are
3086 * interned. String literals are defined in section 3.10.5 of the
3087 * <cite>The Java™ Language Specification</cite>.
3089 * @return a string that has the same contents as this string, but is
3090 * guaranteed to be from a pool of unique strings.
3092 public native String intern();
3095 private static <T> T checkUTF8(T data, String charsetName)
3096 throws UnsupportedEncodingException {
3097 if (charsetName == null) {
3098 throw new NullPointerException("charsetName");
3100 if (!charsetName.equalsIgnoreCase("UTF-8")
3101 && !charsetName.equalsIgnoreCase("UTF8")) {
3102 throw new UnsupportedEncodingException(charsetName);
3107 private static int nextChar(byte[] arr, int[] index) throws IndexOutOfBoundsException {
3108 int c = arr[index[0]++] & 0xff;
3122 /* 110x xxxx 10xx xxxx*/
3123 int char2 = (int) arr[index[0]++];
3124 if ((char2 & 0xC0) != 0x80) {
3125 throw new IndexOutOfBoundsException("malformed input");
3127 return (((c & 0x1F) << 6) | (char2 & 0x3F));
3130 /* 1110 xxxx 10xx xxxx 10xx xxxx */
3131 int char2 = arr[index[0]++];
3132 int char3 = arr[index[0]++];
3133 if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80)) {
3134 throw new IndexOutOfBoundsException("malformed input");
3136 return (((c & 0x0F) << 12)
3137 | ((char2 & 0x3F) << 6)
3138 | ((char3 & 0x3F) << 0));
3141 /* 10xx xxxx, 1111 xxxx */
3142 throw new IndexOutOfBoundsException("malformed input");