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 java.util.Objects;
32 import org.apidesign.bck2brwsr.core.ExtraJavaScript;
33 import org.apidesign.bck2brwsr.core.JavaScriptBody;
34 import org.apidesign.bck2brwsr.core.JavaScriptOnly;
35 import org.apidesign.bck2brwsr.core.JavaScriptPrototype;
36 import org.apidesign.bck2brwsr.emul.lang.System;
39 * The <code>String</code> class represents character strings. All
40 * string literals in Java programs, such as <code>"abc"</code>, are
41 * implemented as instances of this class.
43 * Strings are constant; their values cannot be changed after they
44 * are created. String buffers support mutable strings.
45 * Because String objects are immutable they can be shared. For example:
46 * <p><blockquote><pre>
48 * </pre></blockquote><p>
50 * <p><blockquote><pre>
51 * char data[] = {'a', 'b', 'c'};
52 * String str = new String(data);
53 * </pre></blockquote><p>
54 * Here are some more examples of how strings can be used:
55 * <p><blockquote><pre>
56 * System.out.println("abc");
58 * System.out.println("abc" + cde);
59 * String c = "abc".substring(2,3);
60 * String d = cde.substring(1, 2);
63 * The class <code>String</code> includes methods for examining
64 * individual characters of the sequence, for comparing strings, for
65 * searching strings, for extracting substrings, and for creating a
66 * copy of a string with all characters translated to uppercase or to
67 * lowercase. Case mapping is based on the Unicode Standard version
68 * specified by the {@link java.lang.Character Character} class.
70 * The Java language provides special support for the string
71 * concatenation operator ( + ), and for conversion of
72 * other objects to strings. String concatenation is implemented
73 * through the <code>StringBuilder</code>(or <code>StringBuffer</code>)
74 * class and its <code>append</code> method.
75 * String conversions are implemented through the method
76 * <code>toString</code>, defined by <code>Object</code> and
77 * inherited by all classes in Java. For additional information on
78 * string concatenation and conversion, see Gosling, Joy, and Steele,
79 * <i>The Java Language Specification</i>.
81 * <p> Unless otherwise noted, passing a <tt>null</tt> argument to a constructor
82 * or method in this class will cause a {@link NullPointerException} to be
85 * <p>A <code>String</code> represents a string in the UTF-16 format
86 * in which <em>supplementary characters</em> are represented by <em>surrogate
87 * pairs</em> (see the section <a href="Character.html#unicode">Unicode
88 * Character Representations</a> in the <code>Character</code> class for
90 * Index values refer to <code>char</code> code units, so a supplementary
91 * character uses two positions in a <code>String</code>.
92 * <p>The <code>String</code> class provides methods for dealing with
93 * Unicode code points (i.e., characters), in addition to those for
94 * dealing with Unicode code units (i.e., <code>char</code> values).
97 * @author Arthur van Hoff
98 * @author Martin Buchholz
100 * @see java.lang.Object#toString()
101 * @see java.lang.StringBuffer
102 * @see java.lang.StringBuilder
103 * @see java.nio.charset.Charset
108 resource="/org/apidesign/vm4brwsr/emul/lang/java_lang_String.js",
111 @JavaScriptPrototype(container = "String.prototype", prototype = "new String")
112 public final class String
113 implements java.io.Serializable, Comparable<String>, CharSequence
115 /** real string to delegate to */
118 /** use serialVersionUID from JDK 1.0.2 for interoperability */
119 private static final long serialVersionUID = -6849794470754667710L;
124 @JavaScriptBody(args = {}, body =
125 "var p = vm.java_lang_String(false);\n"
126 + "p.toString = function() {\nreturn this._r().toString();\n};\n"
127 + "p.valueOf = function() {\nreturn this._r().valueOf();\n}\n"
129 private static native void registerToString();
132 * Class String is special cased within the Serialization Stream Protocol.
134 * A String instance is written initially into an ObjectOutputStream in the
137 * <code>TC_STRING</code> (utf String)
139 * The String is written by method <code>DataOutput.writeUTF</code>.
140 * A new handle is generated to refer to all future references to the
141 * string instance within the stream.
143 // private static final ObjectStreamField[] serialPersistentFields =
144 // new ObjectStreamField[0];
147 * Initializes a newly created {@code String} object so that it represents
148 * an empty character sequence. Note that use of this constructor is
149 * unnecessary since Strings are immutable.
156 * Initializes a newly created {@code String} object so that it represents
157 * the same sequence of characters as the argument; in other words, the
158 * newly created string is a copy of the argument string. Unless an
159 * explicit copy of {@code original} is needed, use of this constructor is
160 * unnecessary since Strings are immutable.
165 public String(String original) {
166 this.r = original.toString();
170 * Allocates a new {@code String} so that it represents the sequence of
171 * characters currently contained in the character array argument. The
172 * contents of the character array are copied; subsequent modification of
173 * the character array does not affect the newly created string.
176 * The initial value of the string
178 @JavaScriptBody(args = { "charArr" }, body=
179 "for (var i = 0; i < charArr.length; i++) {\n"
180 + " if (typeof charArr[i] === 'number') charArr[i] = String.fromCharCode(charArr[i]);\n"
182 + "this._r(charArr.join(''));\n"
184 public String(char value[]) {
188 * Allocates a new {@code String} that contains characters from a subarray
189 * of the character array argument. The {@code offset} argument is the
190 * index of the first character of the subarray and the {@code count}
191 * argument specifies the length of the subarray. The contents of the
192 * subarray are copied; subsequent modification of the character array does
193 * not affect the newly created string.
196 * Array that is the source of characters
204 * @throws IndexOutOfBoundsException
205 * If the {@code offset} and {@code count} arguments index
206 * characters outside the bounds of the {@code value} array
208 public String(char value[], int offset, int count) {
209 initFromCharArray(value, offset, count);
212 @JavaScriptBody(args = { "charArr", "off", "cnt" }, body =
213 "var up = off + cnt;\n" +
214 "for (var i = off; i < up; i++) {\n" +
215 " if (typeof charArr[i] === 'number') charArr[i] = String.fromCharCode(charArr[i]);\n" +
217 "this._r(charArr.slice(off, up).join(\"\"));\n"
219 private native void initFromCharArray(char value[], int offset, int count);
222 * Allocates a new {@code String} that contains characters from a subarray
223 * of the <a href="Character.html#unicode">Unicode code point</a> array
224 * argument. The {@code offset} argument is the index of the first code
225 * point of the subarray and the {@code count} argument specifies the
226 * length of the subarray. The contents of the subarray are converted to
227 * {@code char}s; subsequent modification of the {@code int} array does not
228 * affect the newly created string.
231 * Array that is the source of Unicode code points
239 * @throws IllegalArgumentException
240 * If any invalid Unicode code point is found in {@code
243 * @throws IndexOutOfBoundsException
244 * If the {@code offset} and {@code count} arguments index
245 * characters outside the bounds of the {@code codePoints} array
249 public String(int[] codePoints, int offset, int count) {
251 throw new StringIndexOutOfBoundsException(offset);
254 throw new StringIndexOutOfBoundsException(count);
256 // Note: offset or count might be near -1>>>1.
257 if (offset > codePoints.length - count) {
258 throw new StringIndexOutOfBoundsException(offset + count);
261 final int end = offset + count;
263 // Pass 1: Compute precise size of char[]
265 for (int i = offset; i < end; i++) {
266 int c = codePoints[i];
267 if (Character.isBmpCodePoint(c))
269 else if (Character.isValidCodePoint(c))
271 else throw new IllegalArgumentException(Integer.toString(c));
274 // Pass 2: Allocate and fill in char[]
275 final char[] v = new char[n];
277 for (int i = offset, j = 0; i < end; i++, j++) {
278 int c = codePoints[i];
279 if (Character.isBmpCodePoint(c))
282 Character.toSurrogates(c, v, j++);
285 this.r = new String(v, 0, n);
289 * Allocates a new {@code String} constructed from a subarray of an array
290 * of 8-bit integer values.
292 * <p> The {@code offset} argument is the index of the first byte of the
293 * subarray, and the {@code count} argument specifies the length of the
296 * <p> Each {@code byte} in the subarray is converted to a {@code char} as
297 * specified in the method above.
299 * @deprecated This method does not properly convert bytes into characters.
300 * As of JDK 1.1, the preferred way to do this is via the
301 * {@code String} constructors that take a {@link
302 * java.nio.charset.Charset}, charset name, or that use the platform's
306 * The bytes to be converted to characters
309 * The top 8 bits of each 16-bit Unicode code unit
316 * @throws IndexOutOfBoundsException
317 * If the {@code offset} or {@code count} argument is invalid
319 * @see #String(byte[], int)
320 * @see #String(byte[], int, int, java.lang.String)
321 * @see #String(byte[], int, int, java.nio.charset.Charset)
322 * @see #String(byte[], int, int)
323 * @see #String(byte[], java.lang.String)
324 * @see #String(byte[], java.nio.charset.Charset)
325 * @see #String(byte[])
328 public String(byte ascii[], int hibyte, int offset, int count) {
329 checkBounds(ascii, offset, count);
330 char value[] = new char[count];
333 for (int i = count ; i-- > 0 ;) {
334 value[i] = (char) (ascii[i + offset] & 0xff);
338 for (int i = count ; i-- > 0 ;) {
339 value[i] = (char) (hibyte | (ascii[i + offset] & 0xff));
342 initFromCharArray(value, offset, count);
346 * Allocates a new {@code String} containing characters constructed from
347 * an array of 8-bit integer values. Each character <i>c</i>in the
348 * resulting string is constructed from the corresponding component
349 * <i>b</i> in the byte array such that:
352 * <b><i>c</i></b> == (char)(((hibyte & 0xff) << 8)
353 * | (<b><i>b</i></b> & 0xff))
354 * </pre></blockquote>
356 * @deprecated This method does not properly convert bytes into
357 * characters. As of JDK 1.1, the preferred way to do this is via the
358 * {@code String} constructors that take a {@link
359 * java.nio.charset.Charset}, charset name, or that use the platform's
363 * The bytes to be converted to characters
366 * The top 8 bits of each 16-bit Unicode code unit
368 * @see #String(byte[], int, int, java.lang.String)
369 * @see #String(byte[], int, int, java.nio.charset.Charset)
370 * @see #String(byte[], int, int)
371 * @see #String(byte[], java.lang.String)
372 * @see #String(byte[], java.nio.charset.Charset)
373 * @see #String(byte[])
376 public String(byte ascii[], int hibyte) {
377 this(ascii, hibyte, 0, ascii.length);
380 /* Common private utility method used to bounds check the byte array
381 * and requested offset & length values used by the String(byte[],..)
384 private static void checkBounds(byte[] bytes, int offset, int length) {
386 throw new StringIndexOutOfBoundsException(length);
388 throw new StringIndexOutOfBoundsException(offset);
389 if (offset > bytes.length - length)
390 throw new StringIndexOutOfBoundsException(offset + length);
394 * Constructs a new {@code String} by decoding the specified subarray of
395 * bytes using the specified charset. The length of the new {@code String}
396 * is a function of the charset, and hence may not be equal to the length
399 * <p> The behavior of this constructor when the given bytes are not valid
400 * in the given charset is unspecified. The {@link
401 * java.nio.charset.CharsetDecoder} class should be used when more control
402 * over the decoding process is required.
405 * The bytes to be decoded into characters
408 * The index of the first byte to decode
411 * The number of bytes to decode
414 * The name of a supported {@linkplain java.nio.charset.Charset
417 * @throws UnsupportedEncodingException
418 * If the named charset is not supported
420 * @throws IndexOutOfBoundsException
421 * If the {@code offset} and {@code length} arguments index
422 * characters outside the bounds of the {@code bytes} array
426 public String(byte bytes[], int offset, int length, String charsetName)
427 throws UnsupportedEncodingException
429 this(checkUTF8(bytes, charsetName), offset, length);
433 * Constructs a new {@code String} by decoding the specified subarray of
434 * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
435 * The length of the new {@code String} is a function of the charset, and
436 * hence may not be equal to the length of the subarray.
438 * <p> This method always replaces malformed-input and unmappable-character
439 * sequences with this charset's default replacement string. The {@link
440 * java.nio.charset.CharsetDecoder} class should be used when more control
441 * over the decoding process is required.
444 * The bytes to be decoded into characters
447 * The index of the first byte to decode
450 * The number of bytes to decode
453 * The {@linkplain java.nio.charset.Charset charset} to be used to
454 * decode the {@code bytes}
456 * @throws IndexOutOfBoundsException
457 * If the {@code offset} and {@code length} arguments index
458 * characters outside the bounds of the {@code bytes} array
462 /* don't want dependnecy on Charset
463 public String(byte bytes[], int offset, int length, Charset charset) {
465 throw new NullPointerException("charset");
466 checkBounds(bytes, offset, length);
467 char[] v = StringCoding.decode(charset, bytes, offset, length);
469 this.count = v.length;
475 * Constructs a new {@code String} by decoding the specified array of bytes
476 * using the specified {@linkplain java.nio.charset.Charset charset}. The
477 * length of the new {@code String} is a function of the charset, and hence
478 * may not be equal to the length of the byte array.
480 * <p> The behavior of this constructor when the given bytes are not valid
481 * in the given charset is unspecified. The {@link
482 * java.nio.charset.CharsetDecoder} class should be used when more control
483 * over the decoding process is required.
486 * The bytes to be decoded into characters
489 * The name of a supported {@linkplain java.nio.charset.Charset
492 * @throws UnsupportedEncodingException
493 * If the named charset is not supported
497 public String(byte bytes[], String charsetName)
498 throws UnsupportedEncodingException
500 this(bytes, 0, bytes.length, charsetName);
504 * Constructs a new {@code String} by decoding the specified array of
505 * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
506 * The length of the new {@code String} is a function of the charset, and
507 * hence may not be equal to the length of the byte array.
509 * <p> This method always replaces malformed-input and unmappable-character
510 * sequences with this charset's default replacement string. The {@link
511 * java.nio.charset.CharsetDecoder} class should be used when more control
512 * over the decoding process is required.
515 * The bytes to be decoded into characters
518 * The {@linkplain java.nio.charset.Charset charset} to be used to
519 * decode the {@code bytes}
523 /* don't want dep on Charset
524 public String(byte bytes[], Charset charset) {
525 this(bytes, 0, bytes.length, charset);
530 * Constructs a new {@code String} by decoding the specified subarray of
531 * bytes using the platform's default charset. The length of the new
532 * {@code String} is a function of the charset, and hence may not be equal
533 * to the length of the subarray.
535 * <p> The behavior of this constructor when the given bytes are not valid
536 * in the default charset is unspecified. The {@link
537 * java.nio.charset.CharsetDecoder} class should be used when more control
538 * over the decoding process is required.
541 * The bytes to be decoded into characters
544 * The index of the first byte to decode
547 * The number of bytes to decode
549 * @throws IndexOutOfBoundsException
550 * If the {@code offset} and the {@code length} arguments index
551 * characters outside the bounds of the {@code bytes} array
555 public String(byte bytes[], int offset, int length) {
556 checkBounds(bytes, offset, length);
557 char[] v = new char[length];
558 int[] at = { offset };
559 int end = offset + length;
561 while (at[0] < end) {
562 int ch = nextChar(bytes, at);
563 v[chlen++] = (char)ch;
565 initFromCharArray(v, 0, chlen);
569 * Constructs a new {@code String} by decoding the specified array of bytes
570 * using the platform's default charset. The length of the new {@code
571 * String} is a function of the charset, and hence may not be equal to the
572 * length of the byte array.
574 * <p> The behavior of this constructor when the given bytes are not valid
575 * in the default charset is unspecified. The {@link
576 * java.nio.charset.CharsetDecoder} class should be used when more control
577 * over the decoding process is required.
580 * The bytes to be decoded into characters
584 public String(byte bytes[]) {
585 this(bytes, 0, bytes.length);
589 * Allocates a new string that contains the sequence of characters
590 * currently contained in the string buffer argument. The contents of the
591 * string buffer are copied; subsequent modification of the string buffer
592 * does not affect the newly created string.
595 * A {@code StringBuffer}
597 public String(StringBuffer buffer) {
598 this.r = buffer.toString();
602 * Allocates a new string that contains the sequence of characters
603 * currently contained in the string builder argument. The contents of the
604 * string builder are copied; subsequent modification of the string builder
605 * does not affect the newly created string.
607 * <p> This constructor is provided to ease migration to {@code
608 * StringBuilder}. Obtaining a string from a string builder via the {@code
609 * toString} method is likely to run faster and is generally preferred.
612 * A {@code StringBuilder}
616 public String(StringBuilder builder) {
617 this.r = builder.toString();
621 * Returns the length of this string.
622 * The length is equal to the number of <a href="Character.html#unicode">Unicode
623 * code units</a> in the string.
625 * @return the length of the sequence of characters represented by this
628 @JavaScriptBody(args = {}, body = "return this.toString().length;")
629 public int length() {
630 throw new UnsupportedOperationException();
634 * Returns <tt>true</tt> if, and only if, {@link #length()} is <tt>0</tt>.
636 * @return <tt>true</tt> if {@link #length()} is <tt>0</tt>, otherwise
641 @JavaScriptBody(args = {}, body="return this.toString().length === 0;")
642 public boolean isEmpty() {
643 return length() == 0;
647 * Returns the <code>char</code> value at the
648 * specified index. An index ranges from <code>0</code> to
649 * <code>length() - 1</code>. The first <code>char</code> value of the sequence
650 * is at index <code>0</code>, the next at index <code>1</code>,
651 * and so on, as for array indexing.
653 * <p>If the <code>char</code> value specified by the index is a
654 * <a href="Character.html#unicode">surrogate</a>, the surrogate
657 * @param index the index of the <code>char</code> value.
658 * @return the <code>char</code> value at the specified index of this string.
659 * The first <code>char</code> value is at index <code>0</code>.
660 * @exception IndexOutOfBoundsException if the <code>index</code>
661 * argument is negative or not less than the length of this
664 @JavaScriptBody(args = { "index" },
665 body = "return this.toString().charCodeAt(index);"
667 public char charAt(int index) {
668 throw new UnsupportedOperationException();
672 * Returns the character (Unicode code point) at the specified
673 * index. The index refers to <code>char</code> values
674 * (Unicode code units) and ranges from <code>0</code> to
675 * {@link #length()}<code> - 1</code>.
677 * <p> If the <code>char</code> value specified at the given index
678 * is in the high-surrogate range, the following index is less
679 * than the length of this <code>String</code>, and the
680 * <code>char</code> value at the following index is in the
681 * low-surrogate range, then the supplementary code point
682 * corresponding to this surrogate pair is returned. Otherwise,
683 * the <code>char</code> value at the given index is returned.
685 * @param index the index to the <code>char</code> values
686 * @return the code point value of the character at the
688 * @exception IndexOutOfBoundsException if the <code>index</code>
689 * argument is negative or not less than the length of this
693 public int codePointAt(int index) {
694 if ((index < 0) || (index >= length())) {
695 throw new StringIndexOutOfBoundsException(index);
697 return Character.codePointAtImpl(toCharArray(), offset() + index, offset() + length());
701 * Returns the character (Unicode code point) before the specified
702 * index. The index refers to <code>char</code> values
703 * (Unicode code units) and ranges from <code>1</code> to {@link
704 * CharSequence#length() length}.
706 * <p> If the <code>char</code> value at <code>(index - 1)</code>
707 * is in the low-surrogate range, <code>(index - 2)</code> is not
708 * negative, and the <code>char</code> value at <code>(index -
709 * 2)</code> is in the high-surrogate range, then the
710 * supplementary code point value of the surrogate pair is
711 * returned. If the <code>char</code> value at <code>index -
712 * 1</code> is an unpaired low-surrogate or a high-surrogate, the
713 * surrogate value is returned.
715 * @param index the index following the code point that should be returned
716 * @return the Unicode code point value before the given index.
717 * @exception IndexOutOfBoundsException if the <code>index</code>
718 * argument is less than 1 or greater than the length
722 public int codePointBefore(int index) {
724 if ((i < 0) || (i >= length())) {
725 throw new StringIndexOutOfBoundsException(index);
727 return Character.codePointBeforeImpl(toCharArray(), offset() + index, offset());
731 * Returns the number of Unicode code points in the specified text
732 * range of this <code>String</code>. The text range begins at the
733 * specified <code>beginIndex</code> and extends to the
734 * <code>char</code> at index <code>endIndex - 1</code>. Thus the
735 * length (in <code>char</code>s) of the text range is
736 * <code>endIndex-beginIndex</code>. Unpaired surrogates within
737 * the text range count as one code point each.
739 * @param beginIndex the index to the first <code>char</code> of
741 * @param endIndex the index after the last <code>char</code> of
743 * @return the number of Unicode code points in the specified text
745 * @exception IndexOutOfBoundsException if the
746 * <code>beginIndex</code> is negative, or <code>endIndex</code>
747 * is larger than the length of this <code>String</code>, or
748 * <code>beginIndex</code> is larger than <code>endIndex</code>.
751 public int codePointCount(int beginIndex, int endIndex) {
752 if (beginIndex < 0 || endIndex > length() || beginIndex > endIndex) {
753 throw new IndexOutOfBoundsException();
755 return Character.codePointCountImpl(toCharArray(), offset()+beginIndex, endIndex-beginIndex);
759 * Returns the index within this <code>String</code> that is
760 * offset from the given <code>index</code> by
761 * <code>codePointOffset</code> code points. Unpaired surrogates
762 * within the text range given by <code>index</code> and
763 * <code>codePointOffset</code> count as one code point each.
765 * @param index the index to be offset
766 * @param codePointOffset the offset in code points
767 * @return the index within this <code>String</code>
768 * @exception IndexOutOfBoundsException if <code>index</code>
769 * is negative or larger then the length of this
770 * <code>String</code>, or if <code>codePointOffset</code> is positive
771 * and the substring starting with <code>index</code> has fewer
772 * than <code>codePointOffset</code> code points,
773 * or if <code>codePointOffset</code> is negative and the substring
774 * before <code>index</code> has fewer than the absolute value
775 * of <code>codePointOffset</code> code points.
778 public int offsetByCodePoints(int index, int codePointOffset) {
779 if (index < 0 || index > length()) {
780 throw new IndexOutOfBoundsException();
782 return Character.offsetByCodePointsImpl(toCharArray(), offset(), length(),
783 offset()+index, codePointOffset) - offset();
787 * Copy characters from this string into dst starting at dstBegin.
788 * This method doesn't perform any range checking.
790 @JavaScriptBody(args = { "arr", "to" }, body =
791 "var s = this.toString();\n" +
792 "for (var i = 0; i < s.length; i++) {\n" +
793 " arr[to++] = s[i];\n" +
796 void getChars(char dst[], int dstBegin) {
797 System.arraycopy(toCharArray(), offset(), dst, dstBegin, length());
801 * Copies characters from this string into the destination character
804 * The first character to be copied is at index <code>srcBegin</code>;
805 * the last character to be copied is at index <code>srcEnd-1</code>
806 * (thus the total number of characters to be copied is
807 * <code>srcEnd-srcBegin</code>). The characters are copied into the
808 * subarray of <code>dst</code> starting at index <code>dstBegin</code>
809 * and ending at index:
810 * <p><blockquote><pre>
811 * dstbegin + (srcEnd-srcBegin) - 1
812 * </pre></blockquote>
814 * @param srcBegin index of the first character in the string
816 * @param srcEnd index after the last character in the string
818 * @param dst the destination array.
819 * @param dstBegin the start offset in the destination array.
820 * @exception IndexOutOfBoundsException If any of the following
822 * <ul><li><code>srcBegin</code> is negative.
823 * <li><code>srcBegin</code> is greater than <code>srcEnd</code>
824 * <li><code>srcEnd</code> is greater than the length of this
826 * <li><code>dstBegin</code> is negative
827 * <li><code>dstBegin+(srcEnd-srcBegin)</code> is larger than
828 * <code>dst.length</code></ul>
830 @JavaScriptBody(args = { "beg", "end", "arr", "dst" }, body=
831 "var s = this.toString();\n" +
832 "while (beg < end) {\n" +
833 " arr[dst++] = s.charCodeAt(beg++);\n" +
836 public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
838 throw new StringIndexOutOfBoundsException(srcBegin);
840 if (srcEnd > length()) {
841 throw new StringIndexOutOfBoundsException(srcEnd);
843 if (srcBegin > srcEnd) {
844 throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
846 System.arraycopy(toCharArray(), offset() + srcBegin, dst, dstBegin,
851 * Copies characters from this string into the destination byte array. Each
852 * byte receives the 8 low-order bits of the corresponding character. The
853 * eight high-order bits of each character are not copied and do not
854 * participate in the transfer in any way.
856 * <p> The first character to be copied is at index {@code srcBegin}; the
857 * last character to be copied is at index {@code srcEnd-1}. The total
858 * number of characters to be copied is {@code srcEnd-srcBegin}. The
859 * characters, converted to bytes, are copied into the subarray of {@code
860 * dst} starting at index {@code dstBegin} and ending at index:
863 * dstbegin + (srcEnd-srcBegin) - 1
864 * </pre></blockquote>
866 * @deprecated This method does not properly convert characters into
867 * bytes. As of JDK 1.1, the preferred way to do this is via the
868 * {@link #getBytes()} method, which uses the platform's default charset.
871 * Index of the first character in the string to copy
874 * Index after the last character in the string to copy
877 * The destination array
880 * The start offset in the destination array
882 * @throws IndexOutOfBoundsException
883 * If any of the following is true:
885 * <li> {@code srcBegin} is negative
886 * <li> {@code srcBegin} is greater than {@code srcEnd}
887 * <li> {@code srcEnd} is greater than the length of this String
888 * <li> {@code dstBegin} is negative
889 * <li> {@code dstBegin+(srcEnd-srcBegin)} is larger than {@code
894 public void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin) {
896 throw new StringIndexOutOfBoundsException(srcBegin);
898 if (srcEnd > length()) {
899 throw new StringIndexOutOfBoundsException(srcEnd);
901 if (srcBegin > srcEnd) {
902 throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
905 int n = offset() + srcEnd;
906 int i = offset() + srcBegin;
907 char[] val = toCharArray(); /* avoid getfield opcode */
910 dst[j++] = (byte)val[i++];
915 * Encodes this {@code String} into a sequence of bytes using the named
916 * charset, storing the result into a new byte array.
918 * <p> The behavior of this method when this string cannot be encoded in
919 * the given charset is unspecified. The {@link
920 * java.nio.charset.CharsetEncoder} class should be used when more control
921 * over the encoding process is required.
924 * The name of a supported {@linkplain java.nio.charset.Charset
927 * @return The resultant byte array
929 * @throws UnsupportedEncodingException
930 * If the named charset is not supported
934 public byte[] getBytes(String charsetName)
935 throws UnsupportedEncodingException
937 checkUTF8(null, charsetName);
942 * Encodes this {@code String} into a sequence of bytes using the given
943 * {@linkplain java.nio.charset.Charset charset}, storing the result into a
946 * <p> This method always replaces malformed-input and unmappable-character
947 * sequences with this charset's default replacement byte array. The
948 * {@link java.nio.charset.CharsetEncoder} class should be used when more
949 * control over the encoding process is required.
952 * The {@linkplain java.nio.charset.Charset} to be used to encode
955 * @return The resultant byte array
959 /* don't want dep on Charset
960 public byte[] getBytes(Charset charset) {
961 if (charset == null) throw new NullPointerException();
962 return StringCoding.encode(charset, value, offset, count);
967 * Encodes this {@code String} into a sequence of bytes using the
968 * platform's default charset, storing the result into a new byte array.
970 * <p> The behavior of this method when this string cannot be encoded in
971 * the default charset is unspecified. The {@link
972 * java.nio.charset.CharsetEncoder} class should be used when more control
973 * over the encoding process is required.
975 * @return The resultant byte array
979 public byte[] getBytes() {
981 byte[] arr = new byte[len];
982 for (int i = 0, j = 0; j < len; j++) {
983 final int v = charAt(j);
989 arr = System.expandArray(arr, i + 1);
990 arr[i++] = (byte) (0xC0 | (v >> 6));
991 arr[i++] = (byte) (0x80 | (0x3F & v));
994 arr = System.expandArray(arr, i + 2);
995 arr[i++] = (byte) (0xE0 | (v >> 12));
996 arr[i++] = (byte) (0x80 | ((v >> 6) & 0x7F));
997 arr[i++] = (byte) (0x80 | (0x3F & v));
1003 * Compares this string to the specified object. The result is {@code
1004 * true} if and only if the argument is not {@code null} and is a {@code
1005 * String} object that represents the same sequence of characters as this
1009 * The object to compare this {@code String} against
1011 * @return {@code true} if the given object represents a {@code String}
1012 * equivalent to this string, {@code false} otherwise
1014 * @see #compareTo(String)
1015 * @see #equalsIgnoreCase(String)
1017 @JavaScriptBody(args = { "obj" }, body =
1018 "return obj != null && obj.$instOf_java_lang_String && "
1019 + "this.toString() === obj.toString();"
1021 public boolean equals(Object anObject) {
1022 if (this == anObject) {
1025 if (anObject instanceof String) {
1026 String anotherString = (String)anObject;
1028 if (n == anotherString.length()) {
1029 char v1[] = toCharArray();
1030 char v2[] = anotherString.toCharArray();
1032 int j = anotherString.offset();
1034 if (v1[i++] != v2[j++])
1044 * Compares this string to the specified {@code StringBuffer}. The result
1045 * is {@code true} if and only if this {@code String} represents the same
1046 * sequence of characters as the specified {@code StringBuffer}.
1049 * The {@code StringBuffer} to compare this {@code String} against
1051 * @return {@code true} if this {@code String} represents the same
1052 * sequence of characters as the specified {@code StringBuffer},
1053 * {@code false} otherwise
1057 public boolean contentEquals(StringBuffer sb) {
1059 return contentEquals((CharSequence)sb);
1064 * Compares this string to the specified {@code CharSequence}. The result
1065 * is {@code true} if and only if this {@code String} represents the same
1066 * sequence of char values as the specified sequence.
1069 * The sequence to compare this {@code String} against
1071 * @return {@code true} if this {@code String} represents the same
1072 * sequence of char values as the specified sequence, {@code
1077 public boolean contentEquals(CharSequence cs) {
1078 if (length() != cs.length())
1080 // Argument is a StringBuffer, StringBuilder
1081 if (cs instanceof AbstractStringBuilder) {
1082 char v1[] = toCharArray();
1083 char v2[] = ((AbstractStringBuilder)cs).getValue();
1088 if (v1[i++] != v2[j++])
1093 // Argument is a String
1094 if (cs.equals(this))
1096 // Argument is a generic CharSequence
1097 char v1[] = toCharArray();
1102 if (v1[i++] != cs.charAt(j++))
1109 * Compares this {@code String} to another {@code String}, ignoring case
1110 * considerations. Two strings are considered equal ignoring case if they
1111 * are of the same length and corresponding characters in the two strings
1112 * are equal ignoring case.
1114 * <p> Two characters {@code c1} and {@code c2} are considered the same
1115 * ignoring case if at least one of the following is true:
1117 * <li> The two characters are the same (as compared by the
1118 * {@code ==} operator)
1119 * <li> Applying the method {@link
1120 * java.lang.Character#toUpperCase(char)} to each character
1121 * produces the same result
1122 * <li> Applying the method {@link
1123 * java.lang.Character#toLowerCase(char)} to each character
1124 * produces the same result
1127 * @param anotherString
1128 * The {@code String} to compare this {@code String} against
1130 * @return {@code true} if the argument is not {@code null} and it
1131 * represents an equivalent {@code String} ignoring case; {@code
1134 * @see #equals(Object)
1136 public boolean equalsIgnoreCase(String anotherString) {
1137 return (this == anotherString) ? true :
1138 (anotherString != null) && (anotherString.length() == length()) &&
1139 regionMatches(true, 0, anotherString, 0, length());
1143 * Compares two strings lexicographically.
1144 * The comparison is based on the Unicode value of each character in
1145 * the strings. The character sequence represented by this
1146 * <code>String</code> object is compared lexicographically to the
1147 * character sequence represented by the argument string. The result is
1148 * a negative integer if this <code>String</code> object
1149 * lexicographically precedes the argument string. The result is a
1150 * positive integer if this <code>String</code> object lexicographically
1151 * follows the argument string. The result is zero if the strings
1152 * are equal; <code>compareTo</code> returns <code>0</code> exactly when
1153 * the {@link #equals(Object)} method would return <code>true</code>.
1155 * This is the definition of lexicographic ordering. If two strings are
1156 * different, then either they have different characters at some index
1157 * that is a valid index for both strings, or their lengths are different,
1158 * or both. If they have different characters at one or more index
1159 * positions, let <i>k</i> be the smallest such index; then the string
1160 * whose character at position <i>k</i> has the smaller value, as
1161 * determined by using the < operator, lexicographically precedes the
1162 * other string. In this case, <code>compareTo</code> returns the
1163 * difference of the two character values at position <code>k</code> in
1164 * the two string -- that is, the value:
1166 * this.charAt(k)-anotherString.charAt(k)
1167 * </pre></blockquote>
1168 * If there is no index position at which they differ, then the shorter
1169 * string lexicographically precedes the longer string. In this case,
1170 * <code>compareTo</code> returns the difference of the lengths of the
1171 * strings -- that is, the value:
1173 * this.length()-anotherString.length()
1174 * </pre></blockquote>
1176 * @param anotherString the <code>String</code> to be compared.
1177 * @return the value <code>0</code> if the argument string is equal to
1178 * this string; a value less than <code>0</code> if this string
1179 * is lexicographically less than the string argument; and a
1180 * value greater than <code>0</code> if this string is
1181 * lexicographically greater than the string argument.
1183 public int compareTo(String anotherString) {
1184 int len1 = length();
1185 int len2 = anotherString.length();
1186 int n = Math.min(len1, len2);
1187 char v1[] = toCharArray();
1188 char v2[] = anotherString.toCharArray();
1190 int j = anotherString.offset();
1216 * A Comparator that orders <code>String</code> objects as by
1217 * <code>compareToIgnoreCase</code>. This comparator is serializable.
1219 * Note that this Comparator does <em>not</em> take locale into account,
1220 * and will result in an unsatisfactory ordering for certain locales.
1221 * The java.text package provides <em>Collators</em> to allow
1222 * locale-sensitive ordering.
1224 * @see java.text.Collator#compare(String, String)
1227 public static final Comparator<String> CASE_INSENSITIVE_ORDER
1228 = new CaseInsensitiveComparator();
1230 private static int offset() {
1234 private static class CaseInsensitiveComparator
1235 implements Comparator<String>, java.io.Serializable {
1236 // use serialVersionUID from JDK 1.2.2 for interoperability
1237 private static final long serialVersionUID = 8575799808933029326L;
1239 public int compare(String s1, String s2) {
1240 int n1 = s1.length();
1241 int n2 = s2.length();
1242 int min = Math.min(n1, n2);
1243 for (int i = 0; i < min; i++) {
1244 char c1 = s1.charAt(i);
1245 char c2 = s2.charAt(i);
1247 c1 = Character.toUpperCase(c1);
1248 c2 = Character.toUpperCase(c2);
1250 c1 = Character.toLowerCase(c1);
1251 c2 = Character.toLowerCase(c2);
1253 // No overflow because of numeric promotion
1264 * Compares two strings lexicographically, ignoring case
1265 * differences. This method returns an integer whose sign is that of
1266 * calling <code>compareTo</code> with normalized versions of the strings
1267 * where case differences have been eliminated by calling
1268 * <code>Character.toLowerCase(Character.toUpperCase(character))</code> on
1271 * Note that this method does <em>not</em> take locale into account,
1272 * and will result in an unsatisfactory ordering for certain locales.
1273 * The java.text package provides <em>collators</em> to allow
1274 * locale-sensitive ordering.
1276 * @param str the <code>String</code> to be compared.
1277 * @return a negative integer, zero, or a positive integer as the
1278 * specified String is greater than, equal to, or less
1279 * than this String, ignoring case considerations.
1280 * @see java.text.Collator#compare(String, String)
1283 public int compareToIgnoreCase(String str) {
1284 return CASE_INSENSITIVE_ORDER.compare(this, str);
1288 * Tests if two string regions are equal.
1290 * A substring of this <tt>String</tt> object is compared to a substring
1291 * of the argument other. The result is true if these substrings
1292 * represent identical character sequences. The substring of this
1293 * <tt>String</tt> object to be compared begins at index <tt>toffset</tt>
1294 * and has length <tt>len</tt>. The substring of other to be compared
1295 * begins at index <tt>ooffset</tt> and has length <tt>len</tt>. The
1296 * result is <tt>false</tt> if and only if at least one of the following
1298 * <ul><li><tt>toffset</tt> is negative.
1299 * <li><tt>ooffset</tt> is negative.
1300 * <li><tt>toffset+len</tt> is greater than the length of this
1301 * <tt>String</tt> object.
1302 * <li><tt>ooffset+len</tt> is greater than the length of the other
1304 * <li>There is some nonnegative integer <i>k</i> less than <tt>len</tt>
1306 * <tt>this.charAt(toffset+<i>k</i>) != other.charAt(ooffset+<i>k</i>)</tt>
1309 * @param toffset the starting offset of the subregion in this string.
1310 * @param other the string argument.
1311 * @param ooffset the starting offset of the subregion in the string
1313 * @param len the number of characters to compare.
1314 * @return <code>true</code> if the specified subregion of this string
1315 * exactly matches the specified subregion of the string argument;
1316 * <code>false</code> otherwise.
1318 public boolean regionMatches(int toffset, String other, int ooffset,
1320 char ta[] = toCharArray();
1321 int to = offset() + toffset;
1322 char pa[] = other.toCharArray();
1323 int po = other.offset() + ooffset;
1324 // Note: toffset, ooffset, or len might be near -1>>>1.
1325 if ((ooffset < 0) || (toffset < 0) || (toffset > (long)length() - len)
1326 || (ooffset > (long)other.length() - len)) {
1330 if (ta[to++] != pa[po++]) {
1338 * Tests if two string regions are equal.
1340 * A substring of this <tt>String</tt> object is compared to a substring
1341 * of the argument <tt>other</tt>. The result is <tt>true</tt> if these
1342 * substrings represent character sequences that are the same, ignoring
1343 * case if and only if <tt>ignoreCase</tt> is true. The substring of
1344 * this <tt>String</tt> object to be compared begins at index
1345 * <tt>toffset</tt> and has length <tt>len</tt>. The substring of
1346 * <tt>other</tt> to be compared begins at index <tt>ooffset</tt> and
1347 * has length <tt>len</tt>. The result is <tt>false</tt> if and only if
1348 * at least one of the following is true:
1349 * <ul><li><tt>toffset</tt> is negative.
1350 * <li><tt>ooffset</tt> is negative.
1351 * <li><tt>toffset+len</tt> is greater than the length of this
1352 * <tt>String</tt> object.
1353 * <li><tt>ooffset+len</tt> is greater than the length of the other
1355 * <li><tt>ignoreCase</tt> is <tt>false</tt> and there is some nonnegative
1356 * integer <i>k</i> less than <tt>len</tt> such that:
1358 * this.charAt(toffset+k) != other.charAt(ooffset+k)
1359 * </pre></blockquote>
1360 * <li><tt>ignoreCase</tt> is <tt>true</tt> and there is some nonnegative
1361 * integer <i>k</i> less than <tt>len</tt> such that:
1363 * Character.toLowerCase(this.charAt(toffset+k)) !=
1364 Character.toLowerCase(other.charAt(ooffset+k))
1365 * </pre></blockquote>
1368 * Character.toUpperCase(this.charAt(toffset+k)) !=
1369 * Character.toUpperCase(other.charAt(ooffset+k))
1370 * </pre></blockquote>
1373 * @param ignoreCase if <code>true</code>, ignore case when comparing
1375 * @param toffset the starting offset of the subregion in this
1377 * @param other the string argument.
1378 * @param ooffset the starting offset of the subregion in the string
1380 * @param len the number of characters to compare.
1381 * @return <code>true</code> if the specified subregion of this string
1382 * matches the specified subregion of the string argument;
1383 * <code>false</code> otherwise. Whether the matching is exact
1384 * or case insensitive depends on the <code>ignoreCase</code>
1387 public boolean regionMatches(boolean ignoreCase, int toffset,
1388 String other, int ooffset, int len) {
1389 char ta[] = toCharArray();
1390 int to = offset() + toffset;
1391 char pa[] = other.toCharArray();
1392 int po = other.offset() + ooffset;
1393 // Note: toffset, ooffset, or len might be near -1>>>1.
1394 if ((ooffset < 0) || (toffset < 0) || (toffset > (long)length() - len) ||
1395 (ooffset > (long)other.length() - len)) {
1405 // If characters don't match but case may be ignored,
1406 // try converting both characters to uppercase.
1407 // If the results match, then the comparison scan should
1409 char u1 = Character.toUpperCase(c1);
1410 char u2 = Character.toUpperCase(c2);
1414 // Unfortunately, conversion to uppercase does not work properly
1415 // for the Georgian alphabet, which has strange rules about case
1416 // conversion. So we need to make one last check before
1418 if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) {
1428 * Tests if the substring of this string beginning at the
1429 * specified index starts with the specified prefix.
1431 * @param prefix the prefix.
1432 * @param toffset where to begin looking in this string.
1433 * @return <code>true</code> if the character sequence represented by the
1434 * argument is a prefix of the substring of this object starting
1435 * at index <code>toffset</code>; <code>false</code> otherwise.
1436 * The result is <code>false</code> if <code>toffset</code> is
1437 * negative or greater than the length of this
1438 * <code>String</code> object; otherwise the result is the same
1439 * as the result of the expression
1441 * this.substring(toffset).startsWith(prefix)
1444 @JavaScriptBody(args = { "find", "from" }, body=
1445 "find = find.toString();\n" +
1446 "return this.toString().substring(from, from + find.length) === find;\n"
1448 public boolean startsWith(String prefix, int toffset) {
1449 char ta[] = toCharArray();
1450 int to = offset() + toffset;
1451 char pa[] = prefix.toCharArray();
1452 int po = prefix.offset();
1453 int pc = prefix.length();
1454 // Note: toffset might be near -1>>>1.
1455 if ((toffset < 0) || (toffset > length() - pc)) {
1459 if (ta[to++] != pa[po++]) {
1467 * Tests if this string starts with the specified prefix.
1469 * @param prefix the prefix.
1470 * @return <code>true</code> if the character sequence represented by the
1471 * argument is a prefix of the character sequence represented by
1472 * this string; <code>false</code> otherwise.
1473 * Note also that <code>true</code> will be returned if the
1474 * argument is an empty string or is equal to this
1475 * <code>String</code> object as determined by the
1476 * {@link #equals(Object)} method.
1479 public boolean startsWith(String prefix) {
1480 return startsWith(prefix, 0);
1484 * Tests if this string ends with the specified suffix.
1486 * @param suffix the suffix.
1487 * @return <code>true</code> if the character sequence represented by the
1488 * argument is a suffix of the character sequence represented by
1489 * this object; <code>false</code> otherwise. Note that the
1490 * result will be <code>true</code> if the argument is the
1491 * empty string or is equal to this <code>String</code> object
1492 * as determined by the {@link #equals(Object)} method.
1494 public boolean endsWith(String suffix) {
1495 return startsWith(suffix, length() - suffix.length());
1499 * Returns a hash code for this string. The hash code for a
1500 * <code>String</code> object is computed as
1502 * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
1503 * </pre></blockquote>
1504 * using <code>int</code> arithmetic, where <code>s[i]</code> is the
1505 * <i>i</i>th character of the string, <code>n</code> is the length of
1506 * the string, and <code>^</code> indicates exponentiation.
1507 * (The hash value of the empty string is zero.)
1509 * @return a hash code value for this object.
1511 public int hashCode() {
1512 return super.hashCode();
1514 int computeHashCode() {
1516 if (h == 0 && length() > 0) {
1520 for (int i = 0; i < len; i++) {
1521 h = 31*h + charAt(off++);
1528 * Returns the index within this string of the first occurrence of
1529 * the specified character. If a character with value
1530 * <code>ch</code> occurs in the character sequence represented by
1531 * this <code>String</code> object, then the index (in Unicode
1532 * code units) of the first such occurrence is returned. For
1533 * values of <code>ch</code> in the range from 0 to 0xFFFF
1534 * (inclusive), this is the smallest value <i>k</i> such that:
1536 * this.charAt(<i>k</i>) == ch
1537 * </pre></blockquote>
1538 * is true. For other values of <code>ch</code>, it is the
1539 * smallest value <i>k</i> such that:
1541 * this.codePointAt(<i>k</i>) == ch
1542 * </pre></blockquote>
1543 * is true. In either case, if no such character occurs in this
1544 * string, then <code>-1</code> is returned.
1546 * @param ch a character (Unicode code point).
1547 * @return the index of the first occurrence of the character in the
1548 * character sequence represented by this object, or
1549 * <code>-1</code> if the character does not occur.
1551 public int indexOf(int ch) {
1552 return indexOf(ch, 0);
1556 * Returns the index within this string of the first occurrence of the
1557 * specified character, starting the search at the specified index.
1559 * If a character with value <code>ch</code> occurs in the
1560 * character sequence represented by this <code>String</code>
1561 * object at an index no smaller than <code>fromIndex</code>, then
1562 * the index of the first such occurrence is returned. For values
1563 * of <code>ch</code> in the range from 0 to 0xFFFF (inclusive),
1564 * this is the smallest value <i>k</i> such that:
1566 * (this.charAt(<i>k</i>) == ch) && (<i>k</i> >= fromIndex)
1567 * </pre></blockquote>
1568 * is true. For other values of <code>ch</code>, it is the
1569 * smallest value <i>k</i> such that:
1571 * (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> >= fromIndex)
1572 * </pre></blockquote>
1573 * is true. In either case, if no such character occurs in this
1574 * string at or after position <code>fromIndex</code>, then
1575 * <code>-1</code> is returned.
1578 * There is no restriction on the value of <code>fromIndex</code>. If it
1579 * is negative, it has the same effect as if it were zero: this entire
1580 * string may be searched. If it is greater than the length of this
1581 * string, it has the same effect as if it were equal to the length of
1582 * this string: <code>-1</code> is returned.
1584 * <p>All indices are specified in <code>char</code> values
1585 * (Unicode code units).
1587 * @param ch a character (Unicode code point).
1588 * @param fromIndex the index to start the search from.
1589 * @return the index of the first occurrence of the character in the
1590 * character sequence represented by this object that is greater
1591 * than or equal to <code>fromIndex</code>, or <code>-1</code>
1592 * if the character does not occur.
1594 @JavaScriptBody(args = { "ch", "from" }, body =
1595 "if (typeof ch === 'number') ch = String.fromCharCode(ch);\n" +
1596 "return this.toString().indexOf(ch, from);\n"
1598 public int indexOf(int ch, int fromIndex) {
1599 if (fromIndex < 0) {
1601 } else if (fromIndex >= length()) {
1602 // Note: fromIndex might be near -1>>>1.
1606 if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
1607 // handle most cases here (ch is a BMP code point or a
1608 // negative value (invalid code point))
1609 final char[] value = this.toCharArray();
1610 final int offset = this.offset();
1611 final int max = offset + length();
1612 for (int i = offset + fromIndex; i < max ; i++) {
1613 if (value[i] == ch) {
1619 return indexOfSupplementary(ch, fromIndex);
1624 * Handles (rare) calls of indexOf with a supplementary character.
1626 private int indexOfSupplementary(int ch, int fromIndex) {
1627 if (Character.isValidCodePoint(ch)) {
1628 final char[] value = this.toCharArray();
1629 final int offset = this.offset();
1630 final char hi = Character.highSurrogate(ch);
1631 final char lo = Character.lowSurrogate(ch);
1632 final int max = offset + length() - 1;
1633 for (int i = offset + fromIndex; i < max; i++) {
1634 if (value[i] == hi && value[i+1] == lo) {
1643 * Returns the index within this string of the last occurrence of
1644 * the specified character. For values of <code>ch</code> in the
1645 * range from 0 to 0xFFFF (inclusive), the index (in Unicode code
1646 * units) returned is the largest value <i>k</i> such that:
1648 * this.charAt(<i>k</i>) == ch
1649 * </pre></blockquote>
1650 * is true. For other values of <code>ch</code>, it is the
1651 * largest value <i>k</i> such that:
1653 * this.codePointAt(<i>k</i>) == ch
1654 * </pre></blockquote>
1655 * is true. In either case, if no such character occurs in this
1656 * string, then <code>-1</code> is returned. The
1657 * <code>String</code> is searched backwards starting at the last
1660 * @param ch a character (Unicode code point).
1661 * @return the index of the last occurrence of the character in the
1662 * character sequence represented by this object, or
1663 * <code>-1</code> if the character does not occur.
1665 public int lastIndexOf(int ch) {
1666 return lastIndexOf(ch, length() - 1);
1670 * Returns the index within this string of the last occurrence of
1671 * the specified character, searching backward starting at the
1672 * specified index. For values of <code>ch</code> in the range
1673 * from 0 to 0xFFFF (inclusive), the index returned is the largest
1674 * value <i>k</i> such that:
1676 * (this.charAt(<i>k</i>) == ch) && (<i>k</i> <= fromIndex)
1677 * </pre></blockquote>
1678 * is true. For other values of <code>ch</code>, it is the
1679 * largest value <i>k</i> such that:
1681 * (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> <= fromIndex)
1682 * </pre></blockquote>
1683 * is true. In either case, if no such character occurs in this
1684 * string at or before position <code>fromIndex</code>, then
1685 * <code>-1</code> is returned.
1687 * <p>All indices are specified in <code>char</code> values
1688 * (Unicode code units).
1690 * @param ch a character (Unicode code point).
1691 * @param fromIndex the index to start the search from. There is no
1692 * restriction on the value of <code>fromIndex</code>. If it is
1693 * greater than or equal to the length of this string, it has
1694 * the same effect as if it were equal to one less than the
1695 * length of this string: this entire string may be searched.
1696 * If it is negative, it has the same effect as if it were -1:
1698 * @return the index of the last occurrence of the character in the
1699 * character sequence represented by this object that is less
1700 * than or equal to <code>fromIndex</code>, or <code>-1</code>
1701 * if the character does not occur before that point.
1703 @JavaScriptBody(args = { "ch", "from" }, body =
1704 "if (typeof ch === 'number') ch = String.fromCharCode(ch);\n" +
1705 "return this.toString().lastIndexOf(ch, from);"
1707 public int lastIndexOf(int ch, int fromIndex) {
1708 if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
1709 // handle most cases here (ch is a BMP code point or a
1710 // negative value (invalid code point))
1711 final char[] value = this.toCharArray();
1712 final int offset = this.offset();
1713 int i = offset + Math.min(fromIndex, length() - 1);
1714 for (; i >= offset ; i--) {
1715 if (value[i] == ch) {
1721 return lastIndexOfSupplementary(ch, fromIndex);
1726 * Handles (rare) calls of lastIndexOf with a supplementary character.
1728 private int lastIndexOfSupplementary(int ch, int fromIndex) {
1729 if (Character.isValidCodePoint(ch)) {
1730 final char[] value = this.toCharArray();
1731 final int offset = this.offset();
1732 char hi = Character.highSurrogate(ch);
1733 char lo = Character.lowSurrogate(ch);
1734 int i = offset + Math.min(fromIndex, length() - 2);
1735 for (; i >= offset; i--) {
1736 if (value[i] == hi && value[i+1] == lo) {
1745 * Returns the index within this string of the first occurrence of the
1746 * specified substring.
1748 * <p>The returned index is the smallest value <i>k</i> for which:
1750 * this.startsWith(str, <i>k</i>)
1751 * </pre></blockquote>
1752 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1754 * @param str the substring to search for.
1755 * @return the index of the first occurrence of the specified substring,
1756 * or {@code -1} if there is no such occurrence.
1758 public int indexOf(String str) {
1759 return indexOf(str, 0);
1763 * Returns the index within this string of the first occurrence of the
1764 * specified substring, starting at the specified index.
1766 * <p>The returned index is the smallest value <i>k</i> for which:
1768 * <i>k</i> >= fromIndex && this.startsWith(str, <i>k</i>)
1769 * </pre></blockquote>
1770 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1772 * @param str the substring to search for.
1773 * @param fromIndex the index from which to start the search.
1774 * @return the index of the first occurrence of the specified substring,
1775 * starting at the specified index,
1776 * or {@code -1} if there is no such occurrence.
1778 @JavaScriptBody(args = { "str", "fromIndex" }, body =
1779 "return this.toString().indexOf(str.toString(), fromIndex);"
1781 public native int indexOf(String str, int fromIndex);
1784 * Returns the index within this string of the last occurrence of the
1785 * specified substring. The last occurrence of the empty string ""
1786 * is considered to occur at the index value {@code this.length()}.
1788 * <p>The returned index is the largest value <i>k</i> for which:
1790 * this.startsWith(str, <i>k</i>)
1791 * </pre></blockquote>
1792 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1794 * @param str the substring to search for.
1795 * @return the index of the last occurrence of the specified substring,
1796 * or {@code -1} if there is no such occurrence.
1798 public int lastIndexOf(String str) {
1799 return lastIndexOf(str, length());
1803 * Returns the index within this string of the last occurrence of the
1804 * specified substring, searching backward starting at the specified index.
1806 * <p>The returned index is the largest value <i>k</i> for which:
1808 * <i>k</i> <= fromIndex && this.startsWith(str, <i>k</i>)
1809 * </pre></blockquote>
1810 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1812 * @param str the substring to search for.
1813 * @param fromIndex the index to start the search from.
1814 * @return the index of the last occurrence of the specified substring,
1815 * searching backward from the specified index,
1816 * or {@code -1} if there is no such occurrence.
1818 @JavaScriptBody(args = { "s", "from" }, body =
1819 "return this.toString().lastIndexOf(s.toString(), from);"
1821 public int lastIndexOf(String str, int fromIndex) {
1822 return lastIndexOf(toCharArray(), offset(), length(), str.toCharArray(), str.offset(), str.length(), fromIndex);
1826 * Code shared by String and StringBuffer to do searches. The
1827 * source is the character array being searched, and the target
1828 * is the string being searched for.
1830 * @param source the characters being searched.
1831 * @param sourceOffset offset of the source string.
1832 * @param sourceCount count of the source string.
1833 * @param target the characters being searched for.
1834 * @param targetOffset offset of the target string.
1835 * @param targetCount count of the target string.
1836 * @param fromIndex the index to begin searching from.
1838 static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
1839 char[] target, int targetOffset, int targetCount,
1842 * Check arguments; return immediately where possible. For
1843 * consistency, don't check for null str.
1845 int rightIndex = sourceCount - targetCount;
1846 if (fromIndex < 0) {
1849 if (fromIndex > rightIndex) {
1850 fromIndex = rightIndex;
1852 /* Empty string always matches. */
1853 if (targetCount == 0) {
1857 int strLastIndex = targetOffset + targetCount - 1;
1858 char strLastChar = target[strLastIndex];
1859 int min = sourceOffset + targetCount - 1;
1860 int i = min + fromIndex;
1862 startSearchForLastChar:
1864 while (i >= min && source[i] != strLastChar) {
1871 int start = j - (targetCount - 1);
1872 int k = strLastIndex - 1;
1875 if (source[j--] != target[k--]) {
1877 continue startSearchForLastChar;
1880 return start - sourceOffset + 1;
1885 * Returns a new string that is a substring of this string. The
1886 * substring begins with the character at the specified index and
1887 * extends to the end of this string. <p>
1890 * "unhappy".substring(2) returns "happy"
1891 * "Harbison".substring(3) returns "bison"
1892 * "emptiness".substring(9) returns "" (an empty string)
1893 * </pre></blockquote>
1895 * @param beginIndex the beginning index, inclusive.
1896 * @return the specified substring.
1897 * @exception IndexOutOfBoundsException if
1898 * <code>beginIndex</code> is negative or larger than the
1899 * length of this <code>String</code> object.
1901 public String substring(int beginIndex) {
1902 return substring(beginIndex, length());
1906 * Returns a new string that is a substring of this string. The
1907 * substring begins at the specified <code>beginIndex</code> and
1908 * extends to the character at index <code>endIndex - 1</code>.
1909 * Thus the length of the substring is <code>endIndex-beginIndex</code>.
1913 * "hamburger".substring(4, 8) returns "urge"
1914 * "smiles".substring(1, 5) returns "mile"
1915 * </pre></blockquote>
1917 * @param beginIndex the beginning index, inclusive.
1918 * @param endIndex the ending index, exclusive.
1919 * @return the specified substring.
1920 * @exception IndexOutOfBoundsException if the
1921 * <code>beginIndex</code> is negative, or
1922 * <code>endIndex</code> is larger than the length of
1923 * this <code>String</code> object, or
1924 * <code>beginIndex</code> is larger than
1925 * <code>endIndex</code>.
1927 @JavaScriptBody(args = { "beginIndex", "endIndex" }, body =
1928 "return this.toString().substring(beginIndex, endIndex);"
1930 public String substring(int beginIndex, int endIndex) {
1931 if (beginIndex < 0) {
1932 throw new StringIndexOutOfBoundsException(beginIndex);
1934 if (endIndex > length()) {
1935 throw new StringIndexOutOfBoundsException(endIndex);
1937 if (beginIndex > endIndex) {
1938 throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
1940 return ((beginIndex == 0) && (endIndex == length())) ? this :
1941 new String(toCharArray(), offset() + beginIndex, endIndex - beginIndex);
1945 * Returns a new character sequence that is a subsequence of this sequence.
1947 * <p> An invocation of this method of the form
1950 * str.subSequence(begin, end)</pre></blockquote>
1952 * behaves in exactly the same way as the invocation
1955 * str.substring(begin, end)</pre></blockquote>
1957 * This method is defined so that the <tt>String</tt> class can implement
1958 * the {@link CharSequence} interface. </p>
1960 * @param beginIndex the begin index, inclusive.
1961 * @param endIndex the end index, exclusive.
1962 * @return the specified subsequence.
1964 * @throws IndexOutOfBoundsException
1965 * if <tt>beginIndex</tt> or <tt>endIndex</tt> are negative,
1966 * if <tt>endIndex</tt> is greater than <tt>length()</tt>,
1967 * or if <tt>beginIndex</tt> is greater than <tt>startIndex</tt>
1972 public CharSequence subSequence(int beginIndex, int endIndex) {
1973 return this.substring(beginIndex, endIndex);
1977 * Concatenates the specified string to the end of this string.
1979 * If the length of the argument string is <code>0</code>, then this
1980 * <code>String</code> object is returned. Otherwise, a new
1981 * <code>String</code> object is created, representing a character
1982 * sequence that is the concatenation of the character sequence
1983 * represented by this <code>String</code> object and the character
1984 * sequence represented by the argument string.<p>
1987 * "cares".concat("s") returns "caress"
1988 * "to".concat("get").concat("her") returns "together"
1989 * </pre></blockquote>
1991 * @param str the <code>String</code> that is concatenated to the end
1992 * of this <code>String</code>.
1993 * @return a string that represents the concatenation of this object's
1994 * characters followed by the string argument's characters.
1996 public String concat(String str) {
1997 int otherLen = str.length();
1998 if (otherLen == 0) {
2001 char buf[] = new char[length() + otherLen];
2002 getChars(0, length(), buf, 0);
2003 str.getChars(0, otherLen, buf, length());
2004 return new String(buf, 0, length() + otherLen);
2008 * Returns a new string resulting from replacing all occurrences of
2009 * <code>oldChar</code> in this string with <code>newChar</code>.
2011 * If the character <code>oldChar</code> does not occur in the
2012 * character sequence represented by this <code>String</code> object,
2013 * then a reference to this <code>String</code> object is returned.
2014 * Otherwise, a new <code>String</code> object is created that
2015 * represents a character sequence identical to the character sequence
2016 * represented by this <code>String</code> object, except that every
2017 * occurrence of <code>oldChar</code> is replaced by an occurrence
2018 * of <code>newChar</code>.
2022 * "mesquite in your cellar".replace('e', 'o')
2023 * returns "mosquito in your collar"
2024 * "the war of baronets".replace('r', 'y')
2025 * returns "the way of bayonets"
2026 * "sparring with a purple porpoise".replace('p', 't')
2027 * returns "starring with a turtle tortoise"
2028 * "JonL".replace('q', 'x') returns "JonL" (no change)
2029 * </pre></blockquote>
2031 * @param oldChar the old character.
2032 * @param newChar the new character.
2033 * @return a string derived from this string by replacing every
2034 * occurrence of <code>oldChar</code> with <code>newChar</code>.
2036 @JavaScriptBody(args = { "arg1", "arg2" }, body =
2037 "if (typeof arg1 === 'number') arg1 = String.fromCharCode(arg1);\n" +
2038 "if (typeof arg2 === 'number') arg2 = String.fromCharCode(arg2);\n" +
2039 "var s = this.toString();\n" +
2041 " var ret = s.replace(arg1, arg2);\n" +
2042 " if (ret === s) {\n" +
2048 public String replace(char oldChar, char newChar) {
2049 if (oldChar != newChar) {
2052 char[] val = toCharArray(); /* avoid getfield opcode */
2053 int off = offset(); /* avoid getfield opcode */
2056 if (val[off + i] == oldChar) {
2061 char buf[] = new char[len];
2062 for (int j = 0 ; j < i ; j++) {
2063 buf[j] = val[off+j];
2066 char c = val[off + i];
2067 buf[i] = (c == oldChar) ? newChar : c;
2070 return new String(buf, 0, len);
2077 * Tells whether or not this string matches the given <a
2078 * href="../util/regex/Pattern.html#sum">regular expression</a>.
2080 * <p> An invocation of this method of the form
2081 * <i>str</i><tt>.matches(</tt><i>regex</i><tt>)</tt> yields exactly the
2082 * same result as the expression
2084 * <blockquote><tt> {@link java.util.regex.Pattern}.{@link
2085 * java.util.regex.Pattern#matches(String,CharSequence)
2086 * matches}(</tt><i>regex</i><tt>,</tt> <i>str</i><tt>)</tt></blockquote>
2089 * the regular expression to which this string is to be matched
2091 * @return <tt>true</tt> if, and only if, this string matches the
2092 * given regular expression
2094 * @throws PatternSyntaxException
2095 * if the regular expression's syntax is invalid
2097 * @see java.util.regex.Pattern
2102 @JavaScriptBody(args = { "regex" }, body =
2103 "var self = this.toString();\n"
2104 + "var re = new RegExp(regex.toString());\n"
2105 + "var r = re.exec(self);\n"
2106 + "return r != null && r.length > 0 && self.length == r[0].length;"
2108 public boolean matches(String regex) {
2109 throw new UnsupportedOperationException();
2113 * Returns true if and only if this string contains the specified
2114 * sequence of char values.
2116 * @param s the sequence to search for
2117 * @return true if this string contains <code>s</code>, false otherwise
2118 * @throws NullPointerException if <code>s</code> is <code>null</code>
2121 public boolean contains(CharSequence s) {
2122 return indexOf(s.toString()) > -1;
2126 * Replaces the first substring of this string that matches the given <a
2127 * href="../util/regex/Pattern.html#sum">regular expression</a> with the
2128 * given replacement.
2130 * <p> An invocation of this method of the form
2131 * <i>str</i><tt>.replaceFirst(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt>
2132 * yields exactly the same result as the expression
2135 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2136 * compile}(</tt><i>regex</i><tt>).{@link
2137 * java.util.regex.Pattern#matcher(java.lang.CharSequence)
2138 * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceFirst
2139 * replaceFirst}(</tt><i>repl</i><tt>)</tt></blockquote>
2142 * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the
2143 * replacement string may cause the results to be different than if it were
2144 * being treated as a literal replacement string; see
2145 * {@link java.util.regex.Matcher#replaceFirst}.
2146 * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
2147 * meaning of these characters, if desired.
2150 * the regular expression to which this string is to be matched
2151 * @param replacement
2152 * the string to be substituted for the first match
2154 * @return The resulting <tt>String</tt>
2156 * @throws PatternSyntaxException
2157 * if the regular expression's syntax is invalid
2159 * @see java.util.regex.Pattern
2164 @JavaScriptBody(args = { "regex", "newText" }, body =
2165 "var self = this.toString();\n"
2166 + "var re = new RegExp(regex.toString());\n"
2167 + "var r = re.exec(self);\n"
2168 + "if (r === null || r.length === 0) return this;\n"
2169 + "var from = self.indexOf(r[0]);\n"
2170 + "return this.substring(0, from) + newText + this.substring(from + r[0].length);\n"
2172 public String replaceFirst(String regex, String replacement) {
2173 throw new UnsupportedOperationException();
2177 * Replaces each substring of this string that matches the given <a
2178 * href="../util/regex/Pattern.html#sum">regular expression</a> with the
2179 * given replacement.
2181 * <p> An invocation of this method of the form
2182 * <i>str</i><tt>.replaceAll(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt>
2183 * yields exactly the same result as the expression
2186 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2187 * compile}(</tt><i>regex</i><tt>).{@link
2188 * java.util.regex.Pattern#matcher(java.lang.CharSequence)
2189 * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceAll
2190 * replaceAll}(</tt><i>repl</i><tt>)</tt></blockquote>
2193 * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the
2194 * replacement string may cause the results to be different than if it were
2195 * being treated as a literal replacement string; see
2196 * {@link java.util.regex.Matcher#replaceAll Matcher.replaceAll}.
2197 * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
2198 * meaning of these characters, if desired.
2201 * the regular expression to which this string is to be matched
2202 * @param replacement
2203 * the string to be substituted for each match
2205 * @return The resulting <tt>String</tt>
2207 * @throws PatternSyntaxException
2208 * if the regular expression's syntax is invalid
2210 * @see java.util.regex.Pattern
2215 public String replaceAll(String regex, String replacement) {
2218 String n = p.replaceFirst(regex, replacement);
2227 * Replaces each substring of this string that matches the literal target
2228 * sequence with the specified literal replacement sequence. The
2229 * replacement proceeds from the beginning of the string to the end, for
2230 * example, replacing "aa" with "b" in the string "aaa" will result in
2231 * "ba" rather than "ab".
2233 * @param target The sequence of char values to be replaced
2234 * @param replacement The replacement sequence of char values
2235 * @return The resulting string
2236 * @throws NullPointerException if <code>target</code> or
2237 * <code>replacement</code> is <code>null</code>.
2240 @JavaScriptBody(args = { "target", "replacement" }, body =
2241 "var s = this.toString();\n"
2242 + "target = target.toString();\n"
2243 + "replacement = replacement.toString();\n"
2245 + " var ret = s.replace(target, replacement);\n"
2246 + " if (ret === s) {\n"
2252 public native String replace(CharSequence target, CharSequence replacement);
2255 * Splits this string around matches of the given
2256 * <a href="../util/regex/Pattern.html#sum">regular expression</a>.
2258 * <p> The array returned by this method contains each substring of this
2259 * string that is terminated by another substring that matches the given
2260 * expression or is terminated by the end of the string. The substrings in
2261 * the array are in the order in which they occur in this string. If the
2262 * expression does not match any part of the input then the resulting array
2263 * has just one element, namely this string.
2265 * <p> The <tt>limit</tt> parameter controls the number of times the
2266 * pattern is applied and therefore affects the length of the resulting
2267 * array. If the limit <i>n</i> is greater than zero then the pattern
2268 * will be applied at most <i>n</i> - 1 times, the array's
2269 * length will be no greater than <i>n</i>, and the array's last entry
2270 * will contain all input beyond the last matched delimiter. If <i>n</i>
2271 * is non-positive then the pattern will be applied as many times as
2272 * possible and the array can have any length. If <i>n</i> is zero then
2273 * the pattern will be applied as many times as possible, the array can
2274 * have any length, and trailing empty strings will be discarded.
2276 * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the
2277 * following results with these parameters:
2279 * <blockquote><table cellpadding=1 cellspacing=0 summary="Split example showing regex, limit, and result">
2285 * <tr><td align=center>:</td>
2286 * <td align=center>2</td>
2287 * <td><tt>{ "boo", "and:foo" }</tt></td></tr>
2288 * <tr><td align=center>:</td>
2289 * <td align=center>5</td>
2290 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2291 * <tr><td align=center>:</td>
2292 * <td align=center>-2</td>
2293 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2294 * <tr><td align=center>o</td>
2295 * <td align=center>5</td>
2296 * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
2297 * <tr><td align=center>o</td>
2298 * <td align=center>-2</td>
2299 * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
2300 * <tr><td align=center>o</td>
2301 * <td align=center>0</td>
2302 * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
2303 * </table></blockquote>
2305 * <p> An invocation of this method of the form
2306 * <i>str.</i><tt>split(</tt><i>regex</i><tt>,</tt> <i>n</i><tt>)</tt>
2307 * yields the same result as the expression
2310 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2311 * compile}<tt>(</tt><i>regex</i><tt>)</tt>.{@link
2312 * java.util.regex.Pattern#split(java.lang.CharSequence,int)
2313 * split}<tt>(</tt><i>str</i><tt>,</tt> <i>n</i><tt>)</tt>
2318 * the delimiting regular expression
2321 * the result threshold, as described above
2323 * @return the array of strings computed by splitting this string
2324 * around matches of the given regular expression
2326 * @throws PatternSyntaxException
2327 * if the regular expression's syntax is invalid
2329 * @see java.util.regex.Pattern
2334 public String[] split(String regex, int limit) {
2336 Object[] arr = splitImpl(this, regex, Integer.MAX_VALUE);
2337 int to = arr.length;
2339 while (to > 1 && ((String)arr[--to]).isEmpty()) {
2343 String[] ret = new String[to];
2344 System.arraycopy(arr, 0, ret, 0, to);
2347 Object[] arr = splitImpl(this, regex, limit);
2348 String[] ret = new String[arr.length];
2350 for (int i = 0; i < arr.length; i++) {
2351 final String s = (String)arr[i];
2353 pos = indexOf(s, pos) + s.length();
2355 ret[arr.length - 1] += substring(pos);
2360 @JavaScriptBody(args = { "str", "regex", "limit"}, body =
2361 "return str.split(new RegExp(regex), limit);"
2363 private static native Object[] splitImpl(String str, String regex, int limit);
2366 * Splits this string around matches of the given <a
2367 * href="../util/regex/Pattern.html#sum">regular expression</a>.
2369 * <p> This method works as if by invoking the two-argument {@link
2370 * #split(String, int) split} method with the given expression and a limit
2371 * argument of zero. Trailing empty strings are therefore not included in
2372 * the resulting array.
2374 * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the following
2375 * results with these expressions:
2377 * <blockquote><table cellpadding=1 cellspacing=0 summary="Split examples showing regex and result">
2382 * <tr><td align=center>:</td>
2383 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2384 * <tr><td align=center>o</td>
2385 * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
2386 * </table></blockquote>
2390 * the delimiting regular expression
2392 * @return the array of strings computed by splitting this string
2393 * around matches of the given regular expression
2395 * @throws PatternSyntaxException
2396 * if the regular expression's syntax is invalid
2398 * @see java.util.regex.Pattern
2403 public String[] split(String regex) {
2404 return split(regex, 0);
2408 * Converts all of the characters in this <code>String</code> to lower
2409 * case using the rules of the given <code>Locale</code>. Case mapping is based
2410 * on the Unicode Standard version specified by the {@link java.lang.Character Character}
2411 * class. Since case mappings are not always 1:1 char mappings, the resulting
2412 * <code>String</code> may be a different length than the original <code>String</code>.
2414 * Examples of lowercase mappings are in the following table:
2415 * <table border="1" summary="Lowercase mapping examples showing language code of locale, upper case, lower case, and description">
2417 * <th>Language Code of Locale</th>
2418 * <th>Upper Case</th>
2419 * <th>Lower Case</th>
2420 * <th>Description</th>
2423 * <td>tr (Turkish)</td>
2424 * <td>\u0130</td>
2425 * <td>\u0069</td>
2426 * <td>capital letter I with dot above -> small letter i</td>
2429 * <td>tr (Turkish)</td>
2430 * <td>\u0049</td>
2431 * <td>\u0131</td>
2432 * <td>capital letter I -> small letter dotless i </td>
2436 * <td>French Fries</td>
2437 * <td>french fries</td>
2438 * <td>lowercased all chars in String</td>
2442 * <td><img src="doc-files/capiota.gif" alt="capiota"><img src="doc-files/capchi.gif" alt="capchi">
2443 * <img src="doc-files/captheta.gif" alt="captheta"><img src="doc-files/capupsil.gif" alt="capupsil">
2444 * <img src="doc-files/capsigma.gif" alt="capsigma"></td>
2445 * <td><img src="doc-files/iota.gif" alt="iota"><img src="doc-files/chi.gif" alt="chi">
2446 * <img src="doc-files/theta.gif" alt="theta"><img src="doc-files/upsilon.gif" alt="upsilon">
2447 * <img src="doc-files/sigma1.gif" alt="sigma"></td>
2448 * <td>lowercased all chars in String</td>
2452 * @param locale use the case transformation rules for this locale
2453 * @return the <code>String</code>, converted to lowercase.
2454 * @see java.lang.String#toLowerCase()
2455 * @see java.lang.String#toUpperCase()
2456 * @see java.lang.String#toUpperCase(Locale)
2459 public String toLowerCase(java.util.Locale locale) {
2460 return toLowerCase();
2462 // if (locale == null) {
2463 // throw new NullPointerException();
2468 // /* Now check if there are any characters that need to be changed. */
2470 // for (firstUpper = 0 ; firstUpper < count; ) {
2471 // char c = value[offset+firstUpper];
2472 // if ((c >= Character.MIN_HIGH_SURROGATE) &&
2473 // (c <= Character.MAX_HIGH_SURROGATE)) {
2474 // int supplChar = codePointAt(firstUpper);
2475 // if (supplChar != Character.toLowerCase(supplChar)) {
2478 // firstUpper += Character.charCount(supplChar);
2480 // if (c != Character.toLowerCase(c)) {
2489 // char[] result = new char[count];
2490 // int resultOffset = 0; /* result may grow, so i+resultOffset
2491 // * is the write location in result */
2493 // /* Just copy the first few lowerCase characters. */
2494 // System.arraycopy(value, offset, result, 0, firstUpper);
2496 // String lang = locale.getLanguage();
2497 // boolean localeDependent =
2498 // (lang == "tr" || lang == "az" || lang == "lt");
2499 // char[] lowerCharArray;
2503 // for (int i = firstUpper; i < count; i += srcCount) {
2504 // srcChar = (int)value[offset+i];
2505 // if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
2506 // (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
2507 // srcChar = codePointAt(i);
2508 // srcCount = Character.charCount(srcChar);
2512 // if (localeDependent || srcChar == '\u03A3') { // GREEK CAPITAL LETTER SIGMA
2513 // lowerChar = ConditionalSpecialCasing.toLowerCaseEx(this, i, locale);
2514 // } else if (srcChar == '\u0130') { // LATIN CAPITAL LETTER I DOT
2515 // lowerChar = Character.ERROR;
2517 // lowerChar = Character.toLowerCase(srcChar);
2519 // if ((lowerChar == Character.ERROR) ||
2520 // (lowerChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
2521 // if (lowerChar == Character.ERROR) {
2522 // if (!localeDependent && srcChar == '\u0130') {
2524 // ConditionalSpecialCasing.toLowerCaseCharArray(this, i, Locale.ENGLISH);
2527 // ConditionalSpecialCasing.toLowerCaseCharArray(this, i, locale);
2529 // } else if (srcCount == 2) {
2530 // resultOffset += Character.toChars(lowerChar, result, i + resultOffset) - srcCount;
2533 // lowerCharArray = Character.toChars(lowerChar);
2536 // /* Grow result if needed */
2537 // int mapLen = lowerCharArray.length;
2538 // if (mapLen > srcCount) {
2539 // char[] result2 = new char[result.length + mapLen - srcCount];
2540 // System.arraycopy(result, 0, result2, 0,
2541 // i + resultOffset);
2542 // result = result2;
2544 // for (int x=0; x<mapLen; ++x) {
2545 // result[i+resultOffset+x] = lowerCharArray[x];
2547 // resultOffset += (mapLen - srcCount);
2549 // result[i+resultOffset] = (char)lowerChar;
2552 // return new String(0, count+resultOffset, result);
2556 * Converts all of the characters in this <code>String</code> to lower
2557 * case using the rules of the default locale. This is equivalent to calling
2558 * <code>toLowerCase(Locale.getDefault())</code>.
2560 * <b>Note:</b> This method is locale sensitive, and may produce unexpected
2561 * results if used for strings that are intended to be interpreted locale
2563 * Examples are programming language identifiers, protocol keys, and HTML
2565 * For instance, <code>"TITLE".toLowerCase()</code> in a Turkish locale
2566 * returns <code>"t\u005Cu0131tle"</code>, where '\u005Cu0131' is the
2567 * LATIN SMALL LETTER DOTLESS I character.
2568 * To obtain correct results for locale insensitive strings, use
2569 * <code>toLowerCase(Locale.ENGLISH)</code>.
2571 * @return the <code>String</code>, converted to lowercase.
2572 * @see java.lang.String#toLowerCase(Locale)
2574 @JavaScriptBody(args = {}, body = "return this.toLowerCase();")
2575 public String toLowerCase() {
2580 * Converts all of the characters in this <code>String</code> to upper
2581 * case using the rules of the given <code>Locale</code>. Case mapping is based
2582 * on the Unicode Standard version specified by the {@link java.lang.Character Character}
2583 * class. Since case mappings are not always 1:1 char mappings, the resulting
2584 * <code>String</code> may be a different length than the original <code>String</code>.
2586 * Examples of locale-sensitive and 1:M case mappings are in the following table.
2588 * <table border="1" summary="Examples of locale-sensitive and 1:M case mappings. Shows Language code of locale, lower case, upper case, and description.">
2590 * <th>Language Code of Locale</th>
2591 * <th>Lower Case</th>
2592 * <th>Upper Case</th>
2593 * <th>Description</th>
2596 * <td>tr (Turkish)</td>
2597 * <td>\u0069</td>
2598 * <td>\u0130</td>
2599 * <td>small letter i -> capital letter I with dot above</td>
2602 * <td>tr (Turkish)</td>
2603 * <td>\u0131</td>
2604 * <td>\u0049</td>
2605 * <td>small letter dotless i -> capital letter I</td>
2609 * <td>\u00df</td>
2610 * <td>\u0053 \u0053</td>
2611 * <td>small letter sharp s -> two letters: SS</td>
2615 * <td>Fahrvergnügen</td>
2616 * <td>FAHRVERGNÜGEN</td>
2620 * @param locale use the case transformation rules for this locale
2621 * @return the <code>String</code>, converted to uppercase.
2622 * @see java.lang.String#toUpperCase()
2623 * @see java.lang.String#toLowerCase()
2624 * @see java.lang.String#toLowerCase(Locale)
2627 public String toUpperCase(Locale locale) {
2628 return toUpperCase();
2630 /* not for javascript
2631 if (locale == null) {
2632 throw new NullPointerException();
2637 // Now check if there are any characters that need to be changed.
2639 for (firstLower = 0 ; firstLower < count; ) {
2640 int c = (int)value[offset+firstLower];
2642 if ((c >= Character.MIN_HIGH_SURROGATE) &&
2643 (c <= Character.MAX_HIGH_SURROGATE)) {
2644 c = codePointAt(firstLower);
2645 srcCount = Character.charCount(c);
2649 int upperCaseChar = Character.toUpperCaseEx(c);
2650 if ((upperCaseChar == Character.ERROR) ||
2651 (c != upperCaseChar)) {
2654 firstLower += srcCount;
2659 char[] result = new char[count]; /* may grow *
2660 int resultOffset = 0; /* result may grow, so i+resultOffset
2661 * is the write location in result *
2663 /* Just copy the first few upperCase characters. *
2664 System.arraycopy(value, offset, result, 0, firstLower);
2666 String lang = locale.getLanguage();
2667 boolean localeDependent =
2668 (lang == "tr" || lang == "az" || lang == "lt");
2669 char[] upperCharArray;
2673 for (int i = firstLower; i < count; i += srcCount) {
2674 srcChar = (int)value[offset+i];
2675 if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
2676 (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
2677 srcChar = codePointAt(i);
2678 srcCount = Character.charCount(srcChar);
2682 if (localeDependent) {
2683 upperChar = ConditionalSpecialCasing.toUpperCaseEx(this, i, locale);
2685 upperChar = Character.toUpperCaseEx(srcChar);
2687 if ((upperChar == Character.ERROR) ||
2688 (upperChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
2689 if (upperChar == Character.ERROR) {
2690 if (localeDependent) {
2692 ConditionalSpecialCasing.toUpperCaseCharArray(this, i, locale);
2694 upperCharArray = Character.toUpperCaseCharArray(srcChar);
2696 } else if (srcCount == 2) {
2697 resultOffset += Character.toChars(upperChar, result, i + resultOffset) - srcCount;
2700 upperCharArray = Character.toChars(upperChar);
2703 /* Grow result if needed *
2704 int mapLen = upperCharArray.length;
2705 if (mapLen > srcCount) {
2706 char[] result2 = new char[result.length + mapLen - srcCount];
2707 System.arraycopy(result, 0, result2, 0,
2711 for (int x=0; x<mapLen; ++x) {
2712 result[i+resultOffset+x] = upperCharArray[x];
2714 resultOffset += (mapLen - srcCount);
2716 result[i+resultOffset] = (char)upperChar;
2719 return new String(0, count+resultOffset, result);
2724 * Converts all of the characters in this <code>String</code> to upper
2725 * case using the rules of the default locale. This method is equivalent to
2726 * <code>toUpperCase(Locale.getDefault())</code>.
2728 * <b>Note:</b> This method is locale sensitive, and may produce unexpected
2729 * results if used for strings that are intended to be interpreted locale
2731 * Examples are programming language identifiers, protocol keys, and HTML
2733 * For instance, <code>"title".toUpperCase()</code> in a Turkish locale
2734 * returns <code>"T\u005Cu0130TLE"</code>, where '\u005Cu0130' is the
2735 * LATIN CAPITAL LETTER I WITH DOT ABOVE character.
2736 * To obtain correct results for locale insensitive strings, use
2737 * <code>toUpperCase(Locale.ENGLISH)</code>.
2739 * @return the <code>String</code>, converted to uppercase.
2740 * @see java.lang.String#toUpperCase(Locale)
2742 @JavaScriptBody(args = {}, body = "return this.toUpperCase();")
2743 public String toUpperCase() {
2748 * Returns a copy of the string, with leading and trailing whitespace
2751 * If this <code>String</code> object represents an empty character
2752 * sequence, or the first and last characters of character sequence
2753 * represented by this <code>String</code> object both have codes
2754 * greater than <code>'\u0020'</code> (the space character), then a
2755 * reference to this <code>String</code> object is returned.
2757 * Otherwise, if there is no character with a code greater than
2758 * <code>'\u0020'</code> in the string, then a new
2759 * <code>String</code> object representing an empty string is created
2762 * Otherwise, let <i>k</i> be the index of the first character in the
2763 * string whose code is greater than <code>'\u0020'</code>, and let
2764 * <i>m</i> be the index of the last character in the string whose code
2765 * is greater than <code>'\u0020'</code>. A new <code>String</code>
2766 * object is created, representing the substring of this string that
2767 * begins with the character at index <i>k</i> and ends with the
2768 * character at index <i>m</i>-that is, the result of
2769 * <code>this.substring(<i>k</i>, <i>m</i>+1)</code>.
2771 * This method may be used to trim whitespace (as defined above) from
2772 * the beginning and end of a string.
2774 * @return A copy of this string with leading and trailing white
2775 * space removed, or this string if it has no leading or
2776 * trailing white space.
2778 public String trim() {
2781 int off = offset(); /* avoid getfield opcode */
2782 char[] val = toCharArray(); /* avoid getfield opcode */
2784 while ((st < len) && (val[off + st] <= ' ')) {
2787 while ((st < len) && (val[off + len - 1] <= ' ')) {
2790 return ((st > 0) || (len < length())) ? substring(st, len) : this;
2794 * This object (which is already a string!) is itself returned.
2796 * @return the string itself.
2798 @JavaScriptBody(args = {}, body = "return this.toString();")
2799 public String toString() {
2804 * Converts this string to a new character array.
2806 * @return a newly allocated character array whose length is the length
2807 * of this string and whose contents are initialized to contain
2808 * the character sequence represented by this string.
2810 public char[] toCharArray() {
2811 char result[] = new char[length()];
2812 getChars(0, length(), result, 0);
2817 * Returns a formatted string using the specified format string and
2820 * <p> The locale always used is the one returned by {@link
2821 * java.util.Locale#getDefault() Locale.getDefault()}.
2824 * A <a href="../util/Formatter.html#syntax">format string</a>
2827 * Arguments referenced by the format specifiers in the format
2828 * string. If there are more arguments than format specifiers, the
2829 * extra arguments are ignored. The number of arguments is
2830 * variable and may be zero. The maximum number of arguments is
2831 * limited by the maximum dimension of a Java array as defined by
2832 * <cite>The Java™ Virtual Machine Specification</cite>.
2833 * The behaviour on a
2834 * <tt>null</tt> argument depends on the <a
2835 * href="../util/Formatter.html#syntax">conversion</a>.
2837 * @throws IllegalFormatException
2838 * If a format string contains an illegal syntax, a format
2839 * specifier that is incompatible with the given arguments,
2840 * insufficient arguments given the format string, or other
2841 * illegal conditions. For specification of all possible
2842 * formatting errors, see the <a
2843 * href="../util/Formatter.html#detail">Details</a> section of the
2844 * formatter class specification.
2846 * @throws NullPointerException
2847 * If the <tt>format</tt> is <tt>null</tt>
2849 * @return A formatted string
2851 * @see java.util.Formatter
2854 public static String format(String format, Object ... args) {
2855 return format((Locale)null, format, args);
2859 * Returns a formatted string using the specified locale, format string,
2863 * The {@linkplain java.util.Locale locale} to apply during
2864 * formatting. If <tt>l</tt> is <tt>null</tt> then no localization
2868 * A <a href="../util/Formatter.html#syntax">format string</a>
2871 * Arguments referenced by the format specifiers in the format
2872 * string. If there are more arguments than format specifiers, the
2873 * extra arguments are ignored. The number of arguments is
2874 * variable and may be zero. The maximum number of arguments is
2875 * limited by the maximum dimension of a Java array as defined by
2876 * <cite>The Java™ Virtual Machine Specification</cite>.
2877 * The behaviour on a
2878 * <tt>null</tt> argument depends on the <a
2879 * href="../util/Formatter.html#syntax">conversion</a>.
2881 * @throws IllegalFormatException
2882 * If a format string contains an illegal syntax, a format
2883 * specifier that is incompatible with the given arguments,
2884 * insufficient arguments given the format string, or other
2885 * illegal conditions. For specification of all possible
2886 * formatting errors, see the <a
2887 * href="../util/Formatter.html#detail">Details</a> section of the
2888 * formatter class specification
2890 * @throws NullPointerException
2891 * If the <tt>format</tt> is <tt>null</tt>
2893 * @return A formatted string
2895 * @see java.util.Formatter
2898 public static String format(Locale l, String format, Object ... args) {
2900 for (int i = 0; i < args.length; i++) {
2901 p = p.replaceFirst("%s", Objects.toString(args[i]));
2904 // return new Formatter(l).format(format, args).toString();
2908 * Returns the string representation of the <code>Object</code> argument.
2910 * @param obj an <code>Object</code>.
2911 * @return if the argument is <code>null</code>, then a string equal to
2912 * <code>"null"</code>; otherwise, the value of
2913 * <code>obj.toString()</code> is returned.
2914 * @see java.lang.Object#toString()
2916 public static String valueOf(Object obj) {
2917 return (obj == null) ? "null" : obj.toString();
2921 * Returns the string representation of the <code>char</code> array
2922 * argument. The contents of the character array are copied; subsequent
2923 * modification of the character array does not affect the newly
2926 * @param data a <code>char</code> array.
2927 * @return a newly allocated string representing the same sequence of
2928 * characters contained in the character array argument.
2930 public static String valueOf(char data[]) {
2931 return new String(data);
2935 * Returns the string representation of a specific subarray of the
2936 * <code>char</code> array argument.
2938 * The <code>offset</code> argument is the index of the first
2939 * character of the subarray. The <code>count</code> argument
2940 * specifies the length of the subarray. The contents of the subarray
2941 * are copied; subsequent modification of the character array does not
2942 * affect the newly created string.
2944 * @param data the character array.
2945 * @param offset the initial offset into the value of the
2946 * <code>String</code>.
2947 * @param count the length of the value of the <code>String</code>.
2948 * @return a string representing the sequence of characters contained
2949 * in the subarray of the character array argument.
2950 * @exception IndexOutOfBoundsException if <code>offset</code> is
2951 * negative, or <code>count</code> is negative, or
2952 * <code>offset+count</code> is larger than
2953 * <code>data.length</code>.
2955 public static String valueOf(char data[], int offset, int count) {
2956 return new String(data, offset, count);
2960 * Returns a String that represents the character sequence in the
2963 * @param data the character array.
2964 * @param offset initial offset of the subarray.
2965 * @param count length of the subarray.
2966 * @return a <code>String</code> that contains the characters of the
2967 * specified subarray of the character array.
2969 public static String copyValueOf(char data[], int offset, int count) {
2970 // All public String constructors now copy the data.
2971 return new String(data, offset, count);
2975 * Returns a String that represents the character sequence in the
2978 * @param data the character array.
2979 * @return a <code>String</code> that contains the characters of the
2982 public static String copyValueOf(char data[]) {
2983 return copyValueOf(data, 0, data.length);
2987 * Returns the string representation of the <code>boolean</code> argument.
2989 * @param b a <code>boolean</code>.
2990 * @return if the argument is <code>true</code>, a string equal to
2991 * <code>"true"</code> is returned; otherwise, a string equal to
2992 * <code>"false"</code> is returned.
2994 public static String valueOf(boolean b) {
2995 return b ? "true" : "false";
2999 * Returns the string representation of the <code>char</code>
3002 * @param c a <code>char</code>.
3003 * @return a string of length <code>1</code> containing
3004 * as its single character the argument <code>c</code>.
3006 public static String valueOf(char c) {
3008 return new String(data, 0, 1);
3012 * Returns the string representation of the <code>int</code> argument.
3014 * The representation is exactly the one returned by the
3015 * <code>Integer.toString</code> method of one argument.
3017 * @param i an <code>int</code>.
3018 * @return a string representation of the <code>int</code> argument.
3019 * @see java.lang.Integer#toString(int, int)
3021 public static String valueOf(int i) {
3022 return Integer.toString(i);
3026 * Returns the string representation of the <code>long</code> argument.
3028 * The representation is exactly the one returned by the
3029 * <code>Long.toString</code> method of one argument.
3031 * @param l a <code>long</code>.
3032 * @return a string representation of the <code>long</code> argument.
3033 * @see java.lang.Long#toString(long)
3035 public static String valueOf(long l) {
3036 return Long.toString(l);
3040 * Returns the string representation of the <code>float</code> argument.
3042 * The representation is exactly the one returned by the
3043 * <code>Float.toString</code> method of one argument.
3045 * @param f a <code>float</code>.
3046 * @return a string representation of the <code>float</code> argument.
3047 * @see java.lang.Float#toString(float)
3049 public static String valueOf(float f) {
3050 return Float.toString(f);
3054 * Returns the string representation of the <code>double</code> argument.
3056 * The representation is exactly the one returned by the
3057 * <code>Double.toString</code> method of one argument.
3059 * @param d a <code>double</code>.
3060 * @return a string representation of the <code>double</code> argument.
3061 * @see java.lang.Double#toString(double)
3063 public static String valueOf(double d) {
3064 return Double.toString(d);
3068 * Returns a canonical representation for the string object.
3070 * A pool of strings, initially empty, is maintained privately by the
3071 * class <code>String</code>.
3073 * When the intern method is invoked, if the pool already contains a
3074 * string equal to this <code>String</code> object as determined by
3075 * the {@link #equals(Object)} method, then the string from the pool is
3076 * returned. Otherwise, this <code>String</code> object is added to the
3077 * pool and a reference to this <code>String</code> object is returned.
3079 * It follows that for any two strings <code>s</code> and <code>t</code>,
3080 * <code>s.intern() == t.intern()</code> is <code>true</code>
3081 * if and only if <code>s.equals(t)</code> is <code>true</code>.
3083 * All literal strings and string-valued constant expressions are
3084 * interned. String literals are defined in section 3.10.5 of the
3085 * <cite>The Java™ Language Specification</cite>.
3087 * @return a string that has the same contents as this string, but is
3088 * guaranteed to be from a pool of unique strings.
3090 public native String intern();
3093 private static <T> T checkUTF8(T data, String charsetName)
3094 throws UnsupportedEncodingException {
3095 if (charsetName == null) {
3096 throw new NullPointerException("charsetName");
3098 if (!charsetName.equalsIgnoreCase("UTF-8")
3099 && !charsetName.equalsIgnoreCase("UTF8")) {
3100 throw new UnsupportedEncodingException(charsetName);
3105 private static int nextChar(byte[] arr, int[] index) throws IndexOutOfBoundsException {
3106 int c = arr[index[0]++] & 0xff;
3120 /* 110x xxxx 10xx xxxx*/
3121 int char2 = (int) arr[index[0]++];
3122 if ((char2 & 0xC0) != 0x80) {
3123 throw new IndexOutOfBoundsException("malformed input");
3125 return (((c & 0x1F) << 6) | (char2 & 0x3F));
3128 /* 1110 xxxx 10xx xxxx 10xx xxxx */
3129 int char2 = arr[index[0]++];
3130 int char3 = arr[index[0]++];
3131 if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80)) {
3132 throw new IndexOutOfBoundsException("malformed input");
3134 return (((c & 0x0F) << 12)
3135 | ((char2 & 0x3F) << 6)
3136 | ((char3 & 0x3F) << 0));
3139 /* 10xx xxxx, 1111 xxxx */
3140 throw new IndexOutOfBoundsException("malformed input");