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.lang.reflect.InvocationTargetException;
30 import java.lang.reflect.Method;
31 import java.util.Comparator;
32 import java.util.Locale;
33 import org.apidesign.bck2brwsr.core.Exported;
34 import org.apidesign.bck2brwsr.core.ExtraJavaScript;
35 import org.apidesign.bck2brwsr.core.JavaScriptBody;
36 import org.apidesign.bck2brwsr.core.JavaScriptPrototype;
37 import org.apidesign.bck2brwsr.emul.lang.System;
40 * The <code>String</code> class represents character strings. All
41 * string literals in Java programs, such as <code>"abc"</code>, are
42 * implemented as instances of this class.
44 * Strings are constant; their values cannot be changed after they
45 * are created. String buffers support mutable strings.
46 * Because String objects are immutable they can be shared. For example:
47 * <p><blockquote><pre>
49 * </pre></blockquote><p>
51 * <p><blockquote><pre>
52 * char data[] = {'a', 'b', 'c'};
53 * String str = new String(data);
54 * </pre></blockquote><p>
55 * Here are some more examples of how strings can be used:
56 * <p><blockquote><pre>
57 * System.out.println("abc");
59 * System.out.println("abc" + cde);
60 * String c = "abc".substring(2,3);
61 * String d = cde.substring(1, 2);
64 * The class <code>String</code> includes methods for examining
65 * individual characters of the sequence, for comparing strings, for
66 * searching strings, for extracting substrings, and for creating a
67 * copy of a string with all characters translated to uppercase or to
68 * lowercase. Case mapping is based on the Unicode Standard version
69 * specified by the {@link java.lang.Character Character} class.
71 * The Java language provides special support for the string
72 * concatenation operator ( + ), and for conversion of
73 * other objects to strings. String concatenation is implemented
74 * through the <code>StringBuilder</code>(or <code>StringBuffer</code>)
75 * class and its <code>append</code> method.
76 * String conversions are implemented through the method
77 * <code>toString</code>, defined by <code>Object</code> and
78 * inherited by all classes in Java. For additional information on
79 * string concatenation and conversion, see Gosling, Joy, and Steele,
80 * <i>The Java Language Specification</i>.
82 * <p> Unless otherwise noted, passing a <tt>null</tt> argument to a constructor
83 * or method in this class will cause a {@link NullPointerException} to be
86 * <p>A <code>String</code> represents a string in the UTF-16 format
87 * in which <em>supplementary characters</em> are represented by <em>surrogate
88 * pairs</em> (see the section <a href="Character.html#unicode">Unicode
89 * Character Representations</a> in the <code>Character</code> class for
91 * Index values refer to <code>char</code> code units, so a supplementary
92 * character uses two positions in a <code>String</code>.
93 * <p>The <code>String</code> class provides methods for dealing with
94 * Unicode code points (i.e., characters), in addition to those for
95 * dealing with Unicode code units (i.e., <code>char</code> values).
98 * @author Arthur van Hoff
99 * @author Martin Buchholz
101 * @see java.lang.Object#toString()
102 * @see java.lang.StringBuffer
103 * @see java.lang.StringBuilder
104 * @see java.nio.charset.Charset
109 resource="/org/apidesign/vm4brwsr/emul/lang/java_lang_String.js",
112 @JavaScriptPrototype(container = "String.prototype", prototype = "new String")
113 public final class String
114 implements java.io.Serializable, Comparable<String>, CharSequence
116 /** real string to delegate to */
119 /** use serialVersionUID from JDK 1.0.2 for interoperability */
120 private static final long serialVersionUID = -6849794470754667710L;
125 @JavaScriptBody(args = {}, body =
126 "var p = java_lang_String(false);\n"
127 + "p.toString = function() {\nreturn this._r().toString();\n};\n"
128 + "p.valueOf = function() {\nreturn this._r().valueOf();\n}\n"
130 private static native void registerToString();
133 * Class String is special cased within the Serialization Stream Protocol.
135 * A String instance is written initially into an ObjectOutputStream in the
138 * <code>TC_STRING</code> (utf String)
140 * The String is written by method <code>DataOutput.writeUTF</code>.
141 * A new handle is generated to refer to all future references to the
142 * string instance within the stream.
144 // private static final ObjectStreamField[] serialPersistentFields =
145 // new ObjectStreamField[0];
148 * Initializes a newly created {@code String} object so that it represents
149 * an empty character sequence. Note that use of this constructor is
150 * unnecessary since Strings are immutable.
157 * Initializes a newly created {@code String} object so that it represents
158 * the same sequence of characters as the argument; in other words, the
159 * newly created string is a copy of the argument string. Unless an
160 * explicit copy of {@code original} is needed, use of this constructor is
161 * unnecessary since Strings are immutable.
166 public String(String original) {
167 this.r = original.toString();
171 * Allocates a new {@code String} so that it represents the sequence of
172 * characters currently contained in the character array argument. The
173 * contents of the character array are copied; subsequent modification of
174 * the character array does not affect the newly created string.
177 * The initial value of the string
179 @JavaScriptBody(args = { "charArr" }, body=
180 "for (var i = 0; i < charArr.length; i++) {\n"
181 + " if (typeof charArr[i] === 'number') charArr[i] = String.fromCharCode(charArr[i]);\n"
183 + "this._r(charArr.join(''));\n"
185 public String(char value[]) {
189 * Allocates a new {@code String} that contains characters from a subarray
190 * of the character array argument. The {@code offset} argument is the
191 * index of the first character of the subarray and the {@code count}
192 * argument specifies the length of the subarray. The contents of the
193 * subarray are copied; subsequent modification of the character array does
194 * not affect the newly created string.
197 * Array that is the source of characters
205 * @throws IndexOutOfBoundsException
206 * If the {@code offset} and {@code count} arguments index
207 * characters outside the bounds of the {@code value} array
209 public String(char value[], int offset, int count) {
210 initFromCharArray(value, offset, count);
213 @JavaScriptBody(args = { "charArr", "off", "cnt" }, body =
214 "var up = off + cnt;\n" +
215 "for (var i = off; i < up; i++) {\n" +
216 " if (typeof charArr[i] === 'number') charArr[i] = String.fromCharCode(charArr[i]);\n" +
218 "this._r(charArr.slice(off, up).join(\"\"));\n"
220 private native void initFromCharArray(char value[], int offset, int count);
223 * Allocates a new {@code String} that contains characters from a subarray
224 * of the <a href="Character.html#unicode">Unicode code point</a> array
225 * argument. The {@code offset} argument is the index of the first code
226 * point of the subarray and the {@code count} argument specifies the
227 * length of the subarray. The contents of the subarray are converted to
228 * {@code char}s; subsequent modification of the {@code int} array does not
229 * affect the newly created string.
232 * Array that is the source of Unicode code points
240 * @throws IllegalArgumentException
241 * If any invalid Unicode code point is found in {@code
244 * @throws IndexOutOfBoundsException
245 * If the {@code offset} and {@code count} arguments index
246 * characters outside the bounds of the {@code codePoints} array
250 public String(int[] codePoints, int offset, int count) {
252 throw new StringIndexOutOfBoundsException(offset);
255 throw new StringIndexOutOfBoundsException(count);
257 // Note: offset or count might be near -1>>>1.
258 if (offset > codePoints.length - count) {
259 throw new StringIndexOutOfBoundsException(offset + count);
262 final int end = offset + count;
264 // Pass 1: Compute precise size of char[]
266 for (int i = offset; i < end; i++) {
267 int c = codePoints[i];
268 if (Character.isBmpCodePoint(c))
270 else if (Character.isValidCodePoint(c))
272 else throw new IllegalArgumentException(Integer.toString(c));
275 // Pass 2: Allocate and fill in char[]
276 final char[] v = new char[n];
278 for (int i = offset, j = 0; i < end; i++, j++) {
279 int c = codePoints[i];
280 if (Character.isBmpCodePoint(c))
283 Character.toSurrogates(c, v, j++);
286 this.r = new String(v, 0, n);
290 * Allocates a new {@code String} constructed from a subarray of an array
291 * of 8-bit integer values.
293 * <p> The {@code offset} argument is the index of the first byte of the
294 * subarray, and the {@code count} argument specifies the length of the
297 * <p> Each {@code byte} in the subarray is converted to a {@code char} as
298 * specified in the method above.
300 * @deprecated This method does not properly convert bytes into characters.
301 * As of JDK 1.1, the preferred way to do this is via the
302 * {@code String} constructors that take a {@link
303 * java.nio.charset.Charset}, charset name, or that use the platform's
307 * The bytes to be converted to characters
310 * The top 8 bits of each 16-bit Unicode code unit
317 * @throws IndexOutOfBoundsException
318 * If the {@code offset} or {@code count} argument is invalid
320 * @see #String(byte[], int)
321 * @see #String(byte[], int, int, java.lang.String)
322 * @see #String(byte[], int, int, java.nio.charset.Charset)
323 * @see #String(byte[], int, int)
324 * @see #String(byte[], java.lang.String)
325 * @see #String(byte[], java.nio.charset.Charset)
326 * @see #String(byte[])
329 public String(byte ascii[], int hibyte, int offset, int count) {
330 checkBounds(ascii, offset, count);
331 char value[] = new char[count];
334 for (int i = count ; i-- > 0 ;) {
335 value[i] = (char) (ascii[i + offset] & 0xff);
339 for (int i = count ; i-- > 0 ;) {
340 value[i] = (char) (hibyte | (ascii[i + offset] & 0xff));
343 initFromCharArray(value, offset, count);
347 * Allocates a new {@code String} containing characters constructed from
348 * an array of 8-bit integer values. Each character <i>c</i>in the
349 * resulting string is constructed from the corresponding component
350 * <i>b</i> in the byte array such that:
353 * <b><i>c</i></b> == (char)(((hibyte & 0xff) << 8)
354 * | (<b><i>b</i></b> & 0xff))
355 * </pre></blockquote>
357 * @deprecated This method does not properly convert bytes into
358 * characters. As of JDK 1.1, the preferred way to do this is via the
359 * {@code String} constructors that take a {@link
360 * java.nio.charset.Charset}, charset name, or that use the platform's
364 * The bytes to be converted to characters
367 * The top 8 bits of each 16-bit Unicode code unit
369 * @see #String(byte[], int, int, java.lang.String)
370 * @see #String(byte[], int, int, java.nio.charset.Charset)
371 * @see #String(byte[], int, int)
372 * @see #String(byte[], java.lang.String)
373 * @see #String(byte[], java.nio.charset.Charset)
374 * @see #String(byte[])
377 public String(byte ascii[], int hibyte) {
378 this(ascii, hibyte, 0, ascii.length);
381 /* Common private utility method used to bounds check the byte array
382 * and requested offset & length values used by the String(byte[],..)
385 private static void checkBounds(byte[] bytes, int offset, int length) {
387 throw new StringIndexOutOfBoundsException(length);
389 throw new StringIndexOutOfBoundsException(offset);
390 if (offset > bytes.length - length)
391 throw new StringIndexOutOfBoundsException(offset + length);
395 * Constructs a new {@code String} by decoding the specified subarray of
396 * bytes using the specified charset. The length of the new {@code String}
397 * is a function of the charset, and hence may not be equal to the length
400 * <p> The behavior of this constructor when the given bytes are not valid
401 * in the given charset is unspecified. The {@link
402 * java.nio.charset.CharsetDecoder} class should be used when more control
403 * over the decoding process is required.
406 * The bytes to be decoded into characters
409 * The index of the first byte to decode
412 * The number of bytes to decode
415 * The name of a supported {@linkplain java.nio.charset.Charset
418 * @throws UnsupportedEncodingException
419 * If the named charset is not supported
421 * @throws IndexOutOfBoundsException
422 * If the {@code offset} and {@code length} arguments index
423 * characters outside the bounds of the {@code bytes} array
427 public String(byte bytes[], int offset, int length, String charsetName)
428 throws UnsupportedEncodingException
430 this(checkUTF8(bytes, charsetName), offset, length);
434 * Constructs a new {@code String} by decoding the specified subarray of
435 * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
436 * The length of the new {@code String} is a function of the charset, and
437 * hence may not be equal to the length of the subarray.
439 * <p> This method always replaces malformed-input and unmappable-character
440 * sequences with this charset's default replacement string. The {@link
441 * java.nio.charset.CharsetDecoder} class should be used when more control
442 * over the decoding process is required.
445 * The bytes to be decoded into characters
448 * The index of the first byte to decode
451 * The number of bytes to decode
454 * The {@linkplain java.nio.charset.Charset charset} to be used to
455 * decode the {@code bytes}
457 * @throws IndexOutOfBoundsException
458 * If the {@code offset} and {@code length} arguments index
459 * characters outside the bounds of the {@code bytes} array
463 /* don't want dependnecy on Charset
464 public String(byte bytes[], int offset, int length, Charset charset) {
466 throw new NullPointerException("charset");
467 checkBounds(bytes, offset, length);
468 char[] v = StringCoding.decode(charset, bytes, offset, length);
470 this.count = v.length;
476 * Constructs a new {@code String} by decoding the specified array of bytes
477 * using the specified {@linkplain java.nio.charset.Charset charset}. The
478 * length of the new {@code String} is a function of the charset, and hence
479 * may not be equal to the length of the byte array.
481 * <p> The behavior of this constructor when the given bytes are not valid
482 * in the given charset is unspecified. The {@link
483 * java.nio.charset.CharsetDecoder} class should be used when more control
484 * over the decoding process is required.
487 * The bytes to be decoded into characters
490 * The name of a supported {@linkplain java.nio.charset.Charset
493 * @throws UnsupportedEncodingException
494 * If the named charset is not supported
498 public String(byte bytes[], String charsetName)
499 throws UnsupportedEncodingException
501 this(bytes, 0, bytes.length, charsetName);
505 * Constructs a new {@code String} by decoding the specified array of
506 * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
507 * The length of the new {@code String} is a function of the charset, and
508 * hence may not be equal to the length of the byte array.
510 * <p> This method always replaces malformed-input and unmappable-character
511 * sequences with this charset's default replacement string. The {@link
512 * java.nio.charset.CharsetDecoder} class should be used when more control
513 * over the decoding process is required.
516 * The bytes to be decoded into characters
519 * The {@linkplain java.nio.charset.Charset charset} to be used to
520 * decode the {@code bytes}
524 /* don't want dep on Charset
525 public String(byte bytes[], Charset charset) {
526 this(bytes, 0, bytes.length, charset);
531 * Constructs a new {@code String} by decoding the specified subarray of
532 * bytes using the platform's default charset. The length of the new
533 * {@code String} is a function of the charset, and hence may not be equal
534 * to the length of the subarray.
536 * <p> The behavior of this constructor when the given bytes are not valid
537 * in the default charset is unspecified. The {@link
538 * java.nio.charset.CharsetDecoder} class should be used when more control
539 * over the decoding process is required.
542 * The bytes to be decoded into characters
545 * The index of the first byte to decode
548 * The number of bytes to decode
550 * @throws IndexOutOfBoundsException
551 * If the {@code offset} and the {@code length} arguments index
552 * characters outside the bounds of the {@code bytes} array
556 public String(byte bytes[], int offset, int length) {
557 checkBounds(bytes, offset, length);
558 char[] v = new char[length];
559 int[] at = { offset };
560 int end = offset + length;
562 while (at[0] < end) {
563 int ch = nextChar(bytes, at);
564 v[chlen++] = (char)ch;
566 initFromCharArray(v, 0, chlen);
570 * Constructs a new {@code String} by decoding the specified array of bytes
571 * using the platform's default charset. The length of the new {@code
572 * String} is a function of the charset, and hence may not be equal to the
573 * length of the byte array.
575 * <p> The behavior of this constructor when the given bytes are not valid
576 * in the default charset is unspecified. The {@link
577 * java.nio.charset.CharsetDecoder} class should be used when more control
578 * over the decoding process is required.
581 * The bytes to be decoded into characters
585 public String(byte bytes[]) {
586 this(bytes, 0, bytes.length);
590 * Allocates a new string that contains the sequence of characters
591 * currently contained in the string buffer argument. The contents of the
592 * string buffer are copied; subsequent modification of the string buffer
593 * does not affect the newly created string.
596 * A {@code StringBuffer}
598 public String(StringBuffer buffer) {
599 this.r = buffer.toString();
603 * Allocates a new string that contains the sequence of characters
604 * currently contained in the string builder argument. The contents of the
605 * string builder are copied; subsequent modification of the string builder
606 * does not affect the newly created string.
608 * <p> This constructor is provided to ease migration to {@code
609 * StringBuilder}. Obtaining a string from a string builder via the {@code
610 * toString} method is likely to run faster and is generally preferred.
613 * A {@code StringBuilder}
617 public String(StringBuilder builder) {
618 this.r = builder.toString();
622 * Returns the length of this string.
623 * The length is equal to the number of <a href="Character.html#unicode">Unicode
624 * code units</a> in the string.
626 * @return the length of the sequence of characters represented by this
629 @JavaScriptBody(args = {}, body = "return this.toString().length;")
630 public int length() {
631 throw new UnsupportedOperationException();
635 * Returns <tt>true</tt> if, and only if, {@link #length()} is <tt>0</tt>.
637 * @return <tt>true</tt> if {@link #length()} is <tt>0</tt>, otherwise
642 @JavaScriptBody(args = {}, body="return this.toString().length === 0;")
643 public boolean isEmpty() {
644 return length() == 0;
648 * Returns the <code>char</code> value at the
649 * specified index. An index ranges from <code>0</code> to
650 * <code>length() - 1</code>. The first <code>char</code> value of the sequence
651 * is at index <code>0</code>, the next at index <code>1</code>,
652 * and so on, as for array indexing.
654 * <p>If the <code>char</code> value specified by the index is a
655 * <a href="Character.html#unicode">surrogate</a>, the surrogate
658 * @param index the index of the <code>char</code> value.
659 * @return the <code>char</code> value at the specified index of this string.
660 * The first <code>char</code> value is at index <code>0</code>.
661 * @exception IndexOutOfBoundsException if the <code>index</code>
662 * argument is negative or not less than the length of this
665 @JavaScriptBody(args = { "index" },
666 body = "return this.toString().charCodeAt(index);"
668 public char charAt(int index) {
669 throw new UnsupportedOperationException();
673 * Returns the character (Unicode code point) at the specified
674 * index. The index refers to <code>char</code> values
675 * (Unicode code units) and ranges from <code>0</code> to
676 * {@link #length()}<code> - 1</code>.
678 * <p> If the <code>char</code> value specified at the given index
679 * is in the high-surrogate range, the following index is less
680 * than the length of this <code>String</code>, and the
681 * <code>char</code> value at the following index is in the
682 * low-surrogate range, then the supplementary code point
683 * corresponding to this surrogate pair is returned. Otherwise,
684 * the <code>char</code> value at the given index is returned.
686 * @param index the index to the <code>char</code> values
687 * @return the code point value of the character at the
689 * @exception IndexOutOfBoundsException if the <code>index</code>
690 * argument is negative or not less than the length of this
694 public int codePointAt(int index) {
695 if ((index < 0) || (index >= length())) {
696 throw new StringIndexOutOfBoundsException(index);
698 return Character.codePointAtImpl(toCharArray(), offset() + index, offset() + length());
702 * Returns the character (Unicode code point) before the specified
703 * index. The index refers to <code>char</code> values
704 * (Unicode code units) and ranges from <code>1</code> to {@link
705 * CharSequence#length() length}.
707 * <p> If the <code>char</code> value at <code>(index - 1)</code>
708 * is in the low-surrogate range, <code>(index - 2)</code> is not
709 * negative, and the <code>char</code> value at <code>(index -
710 * 2)</code> is in the high-surrogate range, then the
711 * supplementary code point value of the surrogate pair is
712 * returned. If the <code>char</code> value at <code>index -
713 * 1</code> is an unpaired low-surrogate or a high-surrogate, the
714 * surrogate value is returned.
716 * @param index the index following the code point that should be returned
717 * @return the Unicode code point value before the given index.
718 * @exception IndexOutOfBoundsException if the <code>index</code>
719 * argument is less than 1 or greater than the length
723 public int codePointBefore(int index) {
725 if ((i < 0) || (i >= length())) {
726 throw new StringIndexOutOfBoundsException(index);
728 return Character.codePointBeforeImpl(toCharArray(), offset() + index, offset());
732 * Returns the number of Unicode code points in the specified text
733 * range of this <code>String</code>. The text range begins at the
734 * specified <code>beginIndex</code> and extends to the
735 * <code>char</code> at index <code>endIndex - 1</code>. Thus the
736 * length (in <code>char</code>s) of the text range is
737 * <code>endIndex-beginIndex</code>. Unpaired surrogates within
738 * the text range count as one code point each.
740 * @param beginIndex the index to the first <code>char</code> of
742 * @param endIndex the index after the last <code>char</code> of
744 * @return the number of Unicode code points in the specified text
746 * @exception IndexOutOfBoundsException if the
747 * <code>beginIndex</code> is negative, or <code>endIndex</code>
748 * is larger than the length of this <code>String</code>, or
749 * <code>beginIndex</code> is larger than <code>endIndex</code>.
752 public int codePointCount(int beginIndex, int endIndex) {
753 if (beginIndex < 0 || endIndex > length() || beginIndex > endIndex) {
754 throw new IndexOutOfBoundsException();
756 return Character.codePointCountImpl(toCharArray(), offset()+beginIndex, endIndex-beginIndex);
760 * Returns the index within this <code>String</code> that is
761 * offset from the given <code>index</code> by
762 * <code>codePointOffset</code> code points. Unpaired surrogates
763 * within the text range given by <code>index</code> and
764 * <code>codePointOffset</code> count as one code point each.
766 * @param index the index to be offset
767 * @param codePointOffset the offset in code points
768 * @return the index within this <code>String</code>
769 * @exception IndexOutOfBoundsException if <code>index</code>
770 * is negative or larger then the length of this
771 * <code>String</code>, or if <code>codePointOffset</code> is positive
772 * and the substring starting with <code>index</code> has fewer
773 * than <code>codePointOffset</code> code points,
774 * or if <code>codePointOffset</code> is negative and the substring
775 * before <code>index</code> has fewer than the absolute value
776 * of <code>codePointOffset</code> code points.
779 public int offsetByCodePoints(int index, int codePointOffset) {
780 if (index < 0 || index > length()) {
781 throw new IndexOutOfBoundsException();
783 return Character.offsetByCodePointsImpl(toCharArray(), offset(), length(),
784 offset()+index, codePointOffset) - offset();
788 * Copy characters from this string into dst starting at dstBegin.
789 * This method doesn't perform any range checking.
791 @JavaScriptBody(args = { "arr", "to" }, body =
792 "var s = this.toString();\n" +
793 "for (var i = 0; i < s.length; i++) {\n" +
794 " arr[to++] = s[i];\n" +
797 native void getChars(char dst[], int dstBegin);
800 * Copies characters from this string into the destination character
803 * The first character to be copied is at index <code>srcBegin</code>;
804 * the last character to be copied is at index <code>srcEnd-1</code>
805 * (thus the total number of characters to be copied is
806 * <code>srcEnd-srcBegin</code>). The characters are copied into the
807 * subarray of <code>dst</code> starting at index <code>dstBegin</code>
808 * and ending at index:
809 * <p><blockquote><pre>
810 * dstbegin + (srcEnd-srcBegin) - 1
811 * </pre></blockquote>
813 * @param srcBegin index of the first character in the string
815 * @param srcEnd index after the last character in the string
817 * @param dst the destination array.
818 * @param dstBegin the start offset in the destination array.
819 * @exception IndexOutOfBoundsException If any of the following
821 * <ul><li><code>srcBegin</code> is negative.
822 * <li><code>srcBegin</code> is greater than <code>srcEnd</code>
823 * <li><code>srcEnd</code> is greater than the length of this
825 * <li><code>dstBegin</code> is negative
826 * <li><code>dstBegin+(srcEnd-srcBegin)</code> is larger than
827 * <code>dst.length</code></ul>
829 @JavaScriptBody(args = { "beg", "end", "arr", "dst" }, body=
830 "var s = this.toString();\n" +
831 "while (beg < end) {\n" +
832 " arr[dst++] = s.charCodeAt(beg++);\n" +
835 public native void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin);
838 * Copies characters from this string into the destination byte array. Each
839 * byte receives the 8 low-order bits of the corresponding character. The
840 * eight high-order bits of each character are not copied and do not
841 * participate in the transfer in any way.
843 * <p> The first character to be copied is at index {@code srcBegin}; the
844 * last character to be copied is at index {@code srcEnd-1}. The total
845 * number of characters to be copied is {@code srcEnd-srcBegin}. The
846 * characters, converted to bytes, are copied into the subarray of {@code
847 * dst} starting at index {@code dstBegin} and ending at index:
850 * dstbegin + (srcEnd-srcBegin) - 1
851 * </pre></blockquote>
853 * @deprecated This method does not properly convert characters into
854 * bytes. As of JDK 1.1, the preferred way to do this is via the
855 * {@link #getBytes()} method, which uses the platform's default charset.
858 * Index of the first character in the string to copy
861 * Index after the last character in the string to copy
864 * The destination array
867 * The start offset in the destination array
869 * @throws IndexOutOfBoundsException
870 * If any of the following is true:
872 * <li> {@code srcBegin} is negative
873 * <li> {@code srcBegin} is greater than {@code srcEnd}
874 * <li> {@code srcEnd} is greater than the length of this String
875 * <li> {@code dstBegin} is negative
876 * <li> {@code dstBegin+(srcEnd-srcBegin)} is larger than {@code
881 public void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin) {
883 throw new StringIndexOutOfBoundsException(srcBegin);
885 if (srcEnd > length()) {
886 throw new StringIndexOutOfBoundsException(srcEnd);
888 if (srcBegin > srcEnd) {
889 throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
892 int n = offset() + srcEnd;
893 int i = offset() + srcBegin;
896 dst[j++] = (byte)charAt(i++);
901 * Encodes this {@code String} into a sequence of bytes using the named
902 * charset, storing the result into a new byte array.
904 * <p> The behavior of this method when this string cannot be encoded in
905 * the given charset is unspecified. The {@link
906 * java.nio.charset.CharsetEncoder} class should be used when more control
907 * over the encoding process is required.
910 * The name of a supported {@linkplain java.nio.charset.Charset
913 * @return The resultant byte array
915 * @throws UnsupportedEncodingException
916 * If the named charset is not supported
920 public byte[] getBytes(String charsetName)
921 throws UnsupportedEncodingException
923 checkUTF8(null, charsetName);
928 * Encodes this {@code String} into a sequence of bytes using the given
929 * {@linkplain java.nio.charset.Charset charset}, storing the result into a
932 * <p> This method always replaces malformed-input and unmappable-character
933 * sequences with this charset's default replacement byte array. The
934 * {@link java.nio.charset.CharsetEncoder} class should be used when more
935 * control over the encoding process is required.
938 * The {@linkplain java.nio.charset.Charset} to be used to encode
941 * @return The resultant byte array
945 /* don't want dep on Charset
946 public byte[] getBytes(Charset charset) {
947 if (charset == null) throw new NullPointerException();
948 return StringCoding.encode(charset, value, offset, count);
953 * Encodes this {@code String} into a sequence of bytes using the
954 * platform's default charset, storing the result into a new byte array.
956 * <p> The behavior of this method when this string cannot be encoded in
957 * the default charset is unspecified. The {@link
958 * java.nio.charset.CharsetEncoder} class should be used when more control
959 * over the encoding process is required.
961 * @return The resultant byte array
965 public byte[] getBytes() {
967 byte[] arr = new byte[len];
968 for (int i = 0, j = 0; j < len; j++) {
969 final int v = charAt(j);
975 arr = System.expandArray(arr, arr.length + 1);
976 arr[i++] = (byte) (0xC0 | (v >> 6));
977 arr[i++] = (byte) (0x80 | (0x3F & v));
980 arr = System.expandArray(arr, arr.length + 2);
981 arr[i++] = (byte) (0xE0 | (v >> 12));
982 arr[i++] = (byte) (0x80 | ((v >> 6) & 0x7F));
983 arr[i++] = (byte) (0x80 | (0x3F & v));
989 * Compares this string to the specified object. The result is {@code
990 * true} if and only if the argument is not {@code null} and is a {@code
991 * String} object that represents the same sequence of characters as this
995 * The object to compare this {@code String} against
997 * @return {@code true} if the given object represents a {@code String}
998 * equivalent to this string, {@code false} otherwise
1000 * @see #compareTo(String)
1001 * @see #equalsIgnoreCase(String)
1003 @JavaScriptBody(args = { "obj" }, body =
1004 "return obj !== null && obj['$instOf_java_lang_String'] && "
1005 + "this.toString() === obj.toString();"
1007 public native boolean equals(Object anObject);
1010 * Compares this string to the specified {@code StringBuffer}. The result
1011 * is {@code true} if and only if this {@code String} represents the same
1012 * sequence of characters as the specified {@code StringBuffer}.
1015 * The {@code StringBuffer} to compare this {@code String} against
1017 * @return {@code true} if this {@code String} represents the same
1018 * sequence of characters as the specified {@code StringBuffer},
1019 * {@code false} otherwise
1023 public boolean contentEquals(StringBuffer sb) {
1025 return contentEquals((CharSequence)sb);
1030 * Compares this string to the specified {@code CharSequence}. The result
1031 * is {@code true} if and only if this {@code String} represents the same
1032 * sequence of char values as the specified sequence.
1035 * The sequence to compare this {@code String} against
1037 * @return {@code true} if this {@code String} represents the same
1038 * sequence of char values as the specified sequence, {@code
1043 public boolean contentEquals(CharSequence cs) {
1044 if (length() != cs.length())
1046 // Argument is a StringBuffer, StringBuilder
1047 if (cs instanceof AbstractStringBuilder) {
1048 char v2[] = ((AbstractStringBuilder)cs).getValue();
1053 if (this.charAt(i++) != v2[j++])
1058 // Argument is a String
1059 if (cs.equals(this))
1061 // Argument is a generic CharSequence
1066 if (this.charAt(i++) != cs.charAt(j++))
1073 * Compares this {@code String} to another {@code String}, ignoring case
1074 * considerations. Two strings are considered equal ignoring case if they
1075 * are of the same length and corresponding characters in the two strings
1076 * are equal ignoring case.
1078 * <p> Two characters {@code c1} and {@code c2} are considered the same
1079 * ignoring case if at least one of the following is true:
1081 * <li> The two characters are the same (as compared by the
1082 * {@code ==} operator)
1083 * <li> Applying the method {@link
1084 * java.lang.Character#toUpperCase(char)} to each character
1085 * produces the same result
1086 * <li> Applying the method {@link
1087 * java.lang.Character#toLowerCase(char)} to each character
1088 * produces the same result
1091 * @param anotherString
1092 * The {@code String} to compare this {@code String} against
1094 * @return {@code true} if the argument is not {@code null} and it
1095 * represents an equivalent {@code String} ignoring case; {@code
1098 * @see #equals(Object)
1100 public boolean equalsIgnoreCase(String anotherString) {
1101 return (this == anotherString) ? true :
1102 (anotherString != null) && (anotherString.length() == length()) &&
1103 regionMatches(true, 0, anotherString, 0, length());
1107 * Compares two strings lexicographically.
1108 * The comparison is based on the Unicode value of each character in
1109 * the strings. The character sequence represented by this
1110 * <code>String</code> object is compared lexicographically to the
1111 * character sequence represented by the argument string. The result is
1112 * a negative integer if this <code>String</code> object
1113 * lexicographically precedes the argument string. The result is a
1114 * positive integer if this <code>String</code> object lexicographically
1115 * follows the argument string. The result is zero if the strings
1116 * are equal; <code>compareTo</code> returns <code>0</code> exactly when
1117 * the {@link #equals(Object)} method would return <code>true</code>.
1119 * This is the definition of lexicographic ordering. If two strings are
1120 * different, then either they have different characters at some index
1121 * that is a valid index for both strings, or their lengths are different,
1122 * or both. If they have different characters at one or more index
1123 * positions, let <i>k</i> be the smallest such index; then the string
1124 * whose character at position <i>k</i> has the smaller value, as
1125 * determined by using the < operator, lexicographically precedes the
1126 * other string. In this case, <code>compareTo</code> returns the
1127 * difference of the two character values at position <code>k</code> in
1128 * the two string -- that is, the value:
1130 * this.charAt(k)-anotherString.charAt(k)
1131 * </pre></blockquote>
1132 * If there is no index position at which they differ, then the shorter
1133 * string lexicographically precedes the longer string. In this case,
1134 * <code>compareTo</code> returns the difference of the lengths of the
1135 * strings -- that is, the value:
1137 * this.length()-anotherString.length()
1138 * </pre></blockquote>
1140 * @param anotherString the <code>String</code> to be compared.
1141 * @return the value <code>0</code> if the argument string is equal to
1142 * this string; a value less than <code>0</code> if this string
1143 * is lexicographically less than the string argument; and a
1144 * value greater than <code>0</code> if this string is
1145 * lexicographically greater than the string argument.
1147 public int compareTo(String anotherString) {
1148 int len1 = length();
1149 int len2 = anotherString.length();
1150 int n = Math.min(len1, len2);
1152 int j = anotherString.offset();
1158 char c1 = this.charAt(k);
1159 char c2 = anotherString.charAt(k);
1167 char c1 = this.charAt(i++);
1168 char c2 = anotherString.charAt(j++);
1178 * A Comparator that orders <code>String</code> objects as by
1179 * <code>compareToIgnoreCase</code>. This comparator is serializable.
1181 * Note that this Comparator does <em>not</em> take locale into account,
1182 * and will result in an unsatisfactory ordering for certain locales.
1183 * The java.text package provides <em>Collators</em> to allow
1184 * locale-sensitive ordering.
1186 * @see java.text.Collator#compare(String, String)
1189 public static final Comparator<String> CASE_INSENSITIVE_ORDER
1190 = new CaseInsensitiveComparator();
1192 private static int offset() {
1196 private static class CaseInsensitiveComparator
1197 implements Comparator<String>, java.io.Serializable {
1198 // use serialVersionUID from JDK 1.2.2 for interoperability
1199 private static final long serialVersionUID = 8575799808933029326L;
1201 public int compare(String s1, String s2) {
1202 int n1 = s1.length();
1203 int n2 = s2.length();
1204 int min = Math.min(n1, n2);
1205 for (int i = 0; i < min; i++) {
1206 char c1 = s1.charAt(i);
1207 char c2 = s2.charAt(i);
1209 c1 = Character.toUpperCase(c1);
1210 c2 = Character.toUpperCase(c2);
1212 c1 = Character.toLowerCase(c1);
1213 c2 = Character.toLowerCase(c2);
1215 // No overflow because of numeric promotion
1226 * Compares two strings lexicographically, ignoring case
1227 * differences. This method returns an integer whose sign is that of
1228 * calling <code>compareTo</code> with normalized versions of the strings
1229 * where case differences have been eliminated by calling
1230 * <code>Character.toLowerCase(Character.toUpperCase(character))</code> on
1233 * Note that this method does <em>not</em> take locale into account,
1234 * and will result in an unsatisfactory ordering for certain locales.
1235 * The java.text package provides <em>collators</em> to allow
1236 * locale-sensitive ordering.
1238 * @param str the <code>String</code> to be compared.
1239 * @return a negative integer, zero, or a positive integer as the
1240 * specified String is greater than, equal to, or less
1241 * than this String, ignoring case considerations.
1242 * @see java.text.Collator#compare(String, String)
1245 public int compareToIgnoreCase(String str) {
1246 return CASE_INSENSITIVE_ORDER.compare(this, str);
1250 * Tests if two string regions are equal.
1252 * A substring of this <tt>String</tt> object is compared to a substring
1253 * of the argument other. The result is true if these substrings
1254 * represent identical character sequences. The substring of this
1255 * <tt>String</tt> object to be compared begins at index <tt>toffset</tt>
1256 * and has length <tt>len</tt>. The substring of other to be compared
1257 * begins at index <tt>ooffset</tt> and has length <tt>len</tt>. The
1258 * result is <tt>false</tt> if and only if at least one of the following
1260 * <ul><li><tt>toffset</tt> is negative.
1261 * <li><tt>ooffset</tt> is negative.
1262 * <li><tt>toffset+len</tt> is greater than the length of this
1263 * <tt>String</tt> object.
1264 * <li><tt>ooffset+len</tt> is greater than the length of the other
1266 * <li>There is some nonnegative integer <i>k</i> less than <tt>len</tt>
1268 * <tt>this.charAt(toffset+<i>k</i>) != other.charAt(ooffset+<i>k</i>)</tt>
1271 * @param toffset the starting offset of the subregion in this string.
1272 * @param other the string argument.
1273 * @param ooffset the starting offset of the subregion in the string
1275 * @param len the number of characters to compare.
1276 * @return <code>true</code> if the specified subregion of this string
1277 * exactly matches the specified subregion of the string argument;
1278 * <code>false</code> otherwise.
1280 public boolean regionMatches(int toffset, String other, int ooffset,
1282 char ta[] = toCharArray();
1283 int to = offset() + toffset;
1284 char pa[] = other.toCharArray();
1285 int po = other.offset() + ooffset;
1286 // Note: toffset, ooffset, or len might be near -1>>>1.
1287 if ((ooffset < 0) || (toffset < 0) || (toffset > (long)length() - len)
1288 || (ooffset > (long)other.length() - len)) {
1292 if (ta[to++] != pa[po++]) {
1300 * Tests if two string regions are equal.
1302 * A substring of this <tt>String</tt> object is compared to a substring
1303 * of the argument <tt>other</tt>. The result is <tt>true</tt> if these
1304 * substrings represent character sequences that are the same, ignoring
1305 * case if and only if <tt>ignoreCase</tt> is true. The substring of
1306 * this <tt>String</tt> object to be compared begins at index
1307 * <tt>toffset</tt> and has length <tt>len</tt>. The substring of
1308 * <tt>other</tt> to be compared begins at index <tt>ooffset</tt> and
1309 * has length <tt>len</tt>. The result is <tt>false</tt> if and only if
1310 * at least one of the following is true:
1311 * <ul><li><tt>toffset</tt> is negative.
1312 * <li><tt>ooffset</tt> is negative.
1313 * <li><tt>toffset+len</tt> is greater than the length of this
1314 * <tt>String</tt> object.
1315 * <li><tt>ooffset+len</tt> is greater than the length of the other
1317 * <li><tt>ignoreCase</tt> is <tt>false</tt> and there is some nonnegative
1318 * integer <i>k</i> less than <tt>len</tt> such that:
1320 * this.charAt(toffset+k) != other.charAt(ooffset+k)
1321 * </pre></blockquote>
1322 * <li><tt>ignoreCase</tt> is <tt>true</tt> and there is some nonnegative
1323 * integer <i>k</i> less than <tt>len</tt> such that:
1325 * Character.toLowerCase(this.charAt(toffset+k)) !=
1326 Character.toLowerCase(other.charAt(ooffset+k))
1327 * </pre></blockquote>
1330 * Character.toUpperCase(this.charAt(toffset+k)) !=
1331 * Character.toUpperCase(other.charAt(ooffset+k))
1332 * </pre></blockquote>
1335 * @param ignoreCase if <code>true</code>, ignore case when comparing
1337 * @param toffset the starting offset of the subregion in this
1339 * @param other the string argument.
1340 * @param ooffset the starting offset of the subregion in the string
1342 * @param len the number of characters to compare.
1343 * @return <code>true</code> if the specified subregion of this string
1344 * matches the specified subregion of the string argument;
1345 * <code>false</code> otherwise. Whether the matching is exact
1346 * or case insensitive depends on the <code>ignoreCase</code>
1349 public boolean regionMatches(boolean ignoreCase, int toffset,
1350 String other, int ooffset, int len) {
1351 char ta[] = toCharArray();
1352 int to = offset() + toffset;
1353 char pa[] = other.toCharArray();
1354 int po = other.offset() + ooffset;
1355 // Note: toffset, ooffset, or len might be near -1>>>1.
1356 if ((ooffset < 0) || (toffset < 0) || (toffset > (long)length() - len) ||
1357 (ooffset > (long)other.length() - len)) {
1367 // If characters don't match but case may be ignored,
1368 // try converting both characters to uppercase.
1369 // If the results match, then the comparison scan should
1371 char u1 = Character.toUpperCase(c1);
1372 char u2 = Character.toUpperCase(c2);
1376 // Unfortunately, conversion to uppercase does not work properly
1377 // for the Georgian alphabet, which has strange rules about case
1378 // conversion. So we need to make one last check before
1380 if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) {
1390 * Tests if the substring of this string beginning at the
1391 * specified index starts with the specified prefix.
1393 * @param prefix the prefix.
1394 * @param toffset where to begin looking in this string.
1395 * @return <code>true</code> if the character sequence represented by the
1396 * argument is a prefix of the substring of this object starting
1397 * at index <code>toffset</code>; <code>false</code> otherwise.
1398 * The result is <code>false</code> if <code>toffset</code> is
1399 * negative or greater than the length of this
1400 * <code>String</code> object; otherwise the result is the same
1401 * as the result of the expression
1403 * this.substring(toffset).startsWith(prefix)
1406 @JavaScriptBody(args = { "find", "from" }, body=
1407 "find = find.toString();\n" +
1408 "return this.toString().substring(from, from + find.length) === find;\n"
1410 public native boolean startsWith(String prefix, int toffset);
1413 * Tests if this string starts with the specified prefix.
1415 * @param prefix the prefix.
1416 * @return <code>true</code> if the character sequence represented by the
1417 * argument is a prefix of the character sequence represented by
1418 * this string; <code>false</code> otherwise.
1419 * Note also that <code>true</code> will be returned if the
1420 * argument is an empty string or is equal to this
1421 * <code>String</code> object as determined by the
1422 * {@link #equals(Object)} method.
1425 public boolean startsWith(String prefix) {
1426 return startsWith(prefix, 0);
1430 * Tests if this string ends with the specified suffix.
1432 * @param suffix the suffix.
1433 * @return <code>true</code> if the character sequence represented by the
1434 * argument is a suffix of the character sequence represented by
1435 * this object; <code>false</code> otherwise. Note that the
1436 * result will be <code>true</code> if the argument is the
1437 * empty string or is equal to this <code>String</code> object
1438 * as determined by the {@link #equals(Object)} method.
1440 public boolean endsWith(String suffix) {
1441 return startsWith(suffix, length() - suffix.length());
1445 * Returns a hash code for this string. The hash code for a
1446 * <code>String</code> object is computed as
1448 * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
1449 * </pre></blockquote>
1450 * using <code>int</code> arithmetic, where <code>s[i]</code> is the
1451 * <i>i</i>th character of the string, <code>n</code> is the length of
1452 * the string, and <code>^</code> indicates exponentiation.
1453 * (The hash value of the empty string is zero.)
1455 * @return a hash code value for this object.
1457 public int hashCode() {
1458 return super.hashCode();
1460 @Exported int computeHashCode() {
1462 if (h == 0 && length() > 0) {
1466 for (int i = 0; i < len; i++) {
1467 h = 31*h + charAt(off++);
1474 * Returns the index within this string of the first occurrence of
1475 * the specified character. If a character with value
1476 * <code>ch</code> occurs in the character sequence represented by
1477 * this <code>String</code> object, then the index (in Unicode
1478 * code units) of the first such occurrence is returned. For
1479 * values of <code>ch</code> in the range from 0 to 0xFFFF
1480 * (inclusive), this is the smallest value <i>k</i> such that:
1482 * this.charAt(<i>k</i>) == ch
1483 * </pre></blockquote>
1484 * is true. For other values of <code>ch</code>, it is the
1485 * smallest value <i>k</i> such that:
1487 * this.codePointAt(<i>k</i>) == ch
1488 * </pre></blockquote>
1489 * is true. In either case, if no such character occurs in this
1490 * string, then <code>-1</code> is returned.
1492 * @param ch a character (Unicode code point).
1493 * @return the index of the first occurrence of the character in the
1494 * character sequence represented by this object, or
1495 * <code>-1</code> if the character does not occur.
1497 public int indexOf(int ch) {
1498 return indexOf(ch, 0);
1502 * Returns the index within this string of the first occurrence of the
1503 * specified character, starting the search at the specified index.
1505 * If a character with value <code>ch</code> occurs in the
1506 * character sequence represented by this <code>String</code>
1507 * object at an index no smaller than <code>fromIndex</code>, then
1508 * the index of the first such occurrence is returned. For values
1509 * of <code>ch</code> in the range from 0 to 0xFFFF (inclusive),
1510 * this is the smallest value <i>k</i> such that:
1512 * (this.charAt(<i>k</i>) == ch) && (<i>k</i> >= fromIndex)
1513 * </pre></blockquote>
1514 * is true. For other values of <code>ch</code>, it is the
1515 * smallest value <i>k</i> such that:
1517 * (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> >= fromIndex)
1518 * </pre></blockquote>
1519 * is true. In either case, if no such character occurs in this
1520 * string at or after position <code>fromIndex</code>, then
1521 * <code>-1</code> is returned.
1524 * There is no restriction on the value of <code>fromIndex</code>. If it
1525 * is negative, it has the same effect as if it were zero: this entire
1526 * string may be searched. If it is greater than the length of this
1527 * string, it has the same effect as if it were equal to the length of
1528 * this string: <code>-1</code> is returned.
1530 * <p>All indices are specified in <code>char</code> values
1531 * (Unicode code units).
1533 * @param ch a character (Unicode code point).
1534 * @param fromIndex the index to start the search from.
1535 * @return the index of the first occurrence of the character in the
1536 * character sequence represented by this object that is greater
1537 * than or equal to <code>fromIndex</code>, or <code>-1</code>
1538 * if the character does not occur.
1540 @JavaScriptBody(args = { "ch", "from" }, body =
1541 "if (typeof ch === 'number') ch = String.fromCharCode(ch);\n" +
1542 "return this.toString().indexOf(ch, from);\n"
1544 public native int indexOf(int ch, int fromIndex);
1547 * Returns the index within this string of the last occurrence of
1548 * the specified character. For values of <code>ch</code> in the
1549 * range from 0 to 0xFFFF (inclusive), the index (in Unicode code
1550 * units) returned is the largest value <i>k</i> such that:
1552 * this.charAt(<i>k</i>) == ch
1553 * </pre></blockquote>
1554 * is true. For other values of <code>ch</code>, it is the
1555 * largest value <i>k</i> such that:
1557 * this.codePointAt(<i>k</i>) == ch
1558 * </pre></blockquote>
1559 * is true. In either case, if no such character occurs in this
1560 * string, then <code>-1</code> is returned. The
1561 * <code>String</code> is searched backwards starting at the last
1564 * @param ch a character (Unicode code point).
1565 * @return the index of the last occurrence of the character in the
1566 * character sequence represented by this object, or
1567 * <code>-1</code> if the character does not occur.
1569 public int lastIndexOf(int ch) {
1570 return lastIndexOf(ch, length() - 1);
1574 * Returns the index within this string of the last occurrence of
1575 * the specified character, searching backward starting at the
1576 * specified index. For values of <code>ch</code> in the range
1577 * from 0 to 0xFFFF (inclusive), the index returned is the largest
1578 * value <i>k</i> such that:
1580 * (this.charAt(<i>k</i>) == ch) && (<i>k</i> <= fromIndex)
1581 * </pre></blockquote>
1582 * is true. For other values of <code>ch</code>, it is the
1583 * largest value <i>k</i> such that:
1585 * (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> <= fromIndex)
1586 * </pre></blockquote>
1587 * is true. In either case, if no such character occurs in this
1588 * string at or before position <code>fromIndex</code>, then
1589 * <code>-1</code> is returned.
1591 * <p>All indices are specified in <code>char</code> values
1592 * (Unicode code units).
1594 * @param ch a character (Unicode code point).
1595 * @param fromIndex the index to start the search from. There is no
1596 * restriction on the value of <code>fromIndex</code>. If it is
1597 * greater than or equal to the length of this string, it has
1598 * the same effect as if it were equal to one less than the
1599 * length of this string: this entire string may be searched.
1600 * If it is negative, it has the same effect as if it were -1:
1602 * @return the index of the last occurrence of the character in the
1603 * character sequence represented by this object that is less
1604 * than or equal to <code>fromIndex</code>, or <code>-1</code>
1605 * if the character does not occur before that point.
1607 @JavaScriptBody(args = { "ch", "from" }, body =
1608 "if (typeof ch === 'number') ch = String.fromCharCode(ch);\n" +
1609 "return this.toString().lastIndexOf(ch, from);"
1611 public native int lastIndexOf(int ch, int fromIndex);
1614 * Returns the index within this string of the first occurrence of the
1615 * specified substring.
1617 * <p>The returned index is the smallest value <i>k</i> for which:
1619 * this.startsWith(str, <i>k</i>)
1620 * </pre></blockquote>
1621 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1623 * @param str the substring to search for.
1624 * @return the index of the first occurrence of the specified substring,
1625 * or {@code -1} if there is no such occurrence.
1627 public int indexOf(String str) {
1628 return indexOf(str, 0);
1632 * Returns the index within this string of the first occurrence of the
1633 * specified substring, starting at the specified index.
1635 * <p>The returned index is the smallest value <i>k</i> for which:
1637 * <i>k</i> >= fromIndex && this.startsWith(str, <i>k</i>)
1638 * </pre></blockquote>
1639 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1641 * @param str the substring to search for.
1642 * @param fromIndex the index from which to start the search.
1643 * @return the index of the first occurrence of the specified substring,
1644 * starting at the specified index,
1645 * or {@code -1} if there is no such occurrence.
1647 @JavaScriptBody(args = { "str", "fromIndex" }, body =
1648 "return this.toString().indexOf(str.toString(), fromIndex);"
1650 public native int indexOf(String str, int fromIndex);
1653 * Returns the index within this string of the last occurrence of the
1654 * specified substring. The last occurrence of the empty string ""
1655 * is considered to occur at the index value {@code this.length()}.
1657 * <p>The returned index is the largest value <i>k</i> for which:
1659 * this.startsWith(str, <i>k</i>)
1660 * </pre></blockquote>
1661 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1663 * @param str the substring to search for.
1664 * @return the index of the last occurrence of the specified substring,
1665 * or {@code -1} if there is no such occurrence.
1667 public int lastIndexOf(String str) {
1668 return lastIndexOf(str, length());
1672 * Returns the index within this string of the last occurrence of the
1673 * specified substring, searching backward starting at the specified index.
1675 * <p>The returned index is the largest value <i>k</i> for which:
1677 * <i>k</i> <= fromIndex && this.startsWith(str, <i>k</i>)
1678 * </pre></blockquote>
1679 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1681 * @param str the substring to search for.
1682 * @param fromIndex the index to start the search from.
1683 * @return the index of the last occurrence of the specified substring,
1684 * searching backward from the specified index,
1685 * or {@code -1} if there is no such occurrence.
1687 @JavaScriptBody(args = { "s", "from" }, body =
1688 "return this.toString().lastIndexOf(s.toString(), from);"
1690 public native int lastIndexOf(String str, int fromIndex);
1693 * Code shared by String and StringBuffer to do searches. The
1694 * source is the character array being searched, and the target
1695 * is the string being searched for.
1697 * @param source the characters being searched.
1698 * @param sourceOffset offset of the source string.
1699 * @param sourceCount count of the source string.
1700 * @param target the characters being searched for.
1701 * @param targetOffset offset of the target string.
1702 * @param targetCount count of the target string.
1703 * @param fromIndex the index to begin searching from.
1705 static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
1706 char[] target, int targetOffset, int targetCount,
1709 * Check arguments; return immediately where possible. For
1710 * consistency, don't check for null str.
1712 int rightIndex = sourceCount - targetCount;
1713 if (fromIndex < 0) {
1716 if (fromIndex > rightIndex) {
1717 fromIndex = rightIndex;
1719 /* Empty string always matches. */
1720 if (targetCount == 0) {
1724 int strLastIndex = targetOffset + targetCount - 1;
1725 char strLastChar = target[strLastIndex];
1726 int min = sourceOffset + targetCount - 1;
1727 int i = min + fromIndex;
1729 startSearchForLastChar:
1731 while (i >= min && source[i] != strLastChar) {
1738 int start = j - (targetCount - 1);
1739 int k = strLastIndex - 1;
1742 if (source[j--] != target[k--]) {
1744 continue startSearchForLastChar;
1747 return start - sourceOffset + 1;
1752 * Returns a new string that is a substring of this string. The
1753 * substring begins with the character at the specified index and
1754 * extends to the end of this string. <p>
1757 * "unhappy".substring(2) returns "happy"
1758 * "Harbison".substring(3) returns "bison"
1759 * "emptiness".substring(9) returns "" (an empty string)
1760 * </pre></blockquote>
1762 * @param beginIndex the beginning index, inclusive.
1763 * @return the specified substring.
1764 * @exception IndexOutOfBoundsException if
1765 * <code>beginIndex</code> is negative or larger than the
1766 * length of this <code>String</code> object.
1768 public String substring(int beginIndex) {
1769 return substring(beginIndex, length());
1773 * Returns a new string that is a substring of this string. The
1774 * substring begins at the specified <code>beginIndex</code> and
1775 * extends to the character at index <code>endIndex - 1</code>.
1776 * Thus the length of the substring is <code>endIndex-beginIndex</code>.
1780 * "hamburger".substring(4, 8) returns "urge"
1781 * "smiles".substring(1, 5) returns "mile"
1782 * </pre></blockquote>
1784 * @param beginIndex the beginning index, inclusive.
1785 * @param endIndex the ending index, exclusive.
1786 * @return the specified substring.
1787 * @exception IndexOutOfBoundsException if the
1788 * <code>beginIndex</code> is negative, or
1789 * <code>endIndex</code> is larger than the length of
1790 * this <code>String</code> object, or
1791 * <code>beginIndex</code> is larger than
1792 * <code>endIndex</code>.
1794 @JavaScriptBody(args = { "beginIndex", "endIndex" }, body =
1795 "return this.toString().substring(beginIndex, endIndex);"
1797 public native String substring(int beginIndex, int endIndex);
1800 * Returns a new character sequence that is a subsequence of this sequence.
1802 * <p> An invocation of this method of the form
1805 * str.subSequence(begin, end)</pre></blockquote>
1807 * behaves in exactly the same way as the invocation
1810 * str.substring(begin, end)</pre></blockquote>
1812 * This method is defined so that the <tt>String</tt> class can implement
1813 * the {@link CharSequence} interface. </p>
1815 * @param beginIndex the begin index, inclusive.
1816 * @param endIndex the end index, exclusive.
1817 * @return the specified subsequence.
1819 * @throws IndexOutOfBoundsException
1820 * if <tt>beginIndex</tt> or <tt>endIndex</tt> are negative,
1821 * if <tt>endIndex</tt> is greater than <tt>length()</tt>,
1822 * or if <tt>beginIndex</tt> is greater than <tt>startIndex</tt>
1827 public CharSequence subSequence(int beginIndex, int endIndex) {
1828 return this.substring(beginIndex, endIndex);
1832 * Concatenates the specified string to the end of this string.
1834 * If the length of the argument string is <code>0</code>, then this
1835 * <code>String</code> object is returned. Otherwise, a new
1836 * <code>String</code> object is created, representing a character
1837 * sequence that is the concatenation of the character sequence
1838 * represented by this <code>String</code> object and the character
1839 * sequence represented by the argument string.<p>
1842 * "cares".concat("s") returns "caress"
1843 * "to".concat("get").concat("her") returns "together"
1844 * </pre></blockquote>
1846 * @param str the <code>String</code> that is concatenated to the end
1847 * of this <code>String</code>.
1848 * @return a string that represents the concatenation of this object's
1849 * characters followed by the string argument's characters.
1851 public String concat(String str) {
1852 int otherLen = str.length();
1853 if (otherLen == 0) {
1856 char buf[] = new char[length() + otherLen];
1857 getChars(0, length(), buf, 0);
1858 str.getChars(0, otherLen, buf, length());
1859 return new String(buf, 0, length() + otherLen);
1863 * Returns a new string resulting from replacing all occurrences of
1864 * <code>oldChar</code> in this string with <code>newChar</code>.
1866 * If the character <code>oldChar</code> does not occur in the
1867 * character sequence represented by this <code>String</code> object,
1868 * then a reference to this <code>String</code> object is returned.
1869 * Otherwise, a new <code>String</code> object is created that
1870 * represents a character sequence identical to the character sequence
1871 * represented by this <code>String</code> object, except that every
1872 * occurrence of <code>oldChar</code> is replaced by an occurrence
1873 * of <code>newChar</code>.
1877 * "mesquite in your cellar".replace('e', 'o')
1878 * returns "mosquito in your collar"
1879 * "the war of baronets".replace('r', 'y')
1880 * returns "the way of bayonets"
1881 * "sparring with a purple porpoise".replace('p', 't')
1882 * returns "starring with a turtle tortoise"
1883 * "JonL".replace('q', 'x') returns "JonL" (no change)
1884 * </pre></blockquote>
1886 * @param oldChar the old character.
1887 * @param newChar the new character.
1888 * @return a string derived from this string by replacing every
1889 * occurrence of <code>oldChar</code> with <code>newChar</code>.
1891 @JavaScriptBody(args = { "arg1", "arg2" }, body =
1892 "if (typeof arg1 === 'number') arg1 = String.fromCharCode(arg1);\n" +
1893 "if (typeof arg2 === 'number') arg2 = String.fromCharCode(arg2);\n" +
1894 "var s = this.toString();\n" +
1896 " var ret = s.replace(arg1, arg2);\n" +
1897 " if (ret === s) {\n" +
1903 public native String replace(char oldChar, char newChar);
1906 * Tells whether or not this string matches the given <a
1907 * href="../util/regex/Pattern.html#sum">regular expression</a>.
1909 * <p> An invocation of this method of the form
1910 * <i>str</i><tt>.matches(</tt><i>regex</i><tt>)</tt> yields exactly the
1911 * same result as the expression
1913 * <blockquote><tt> {@link java.util.regex.Pattern}.{@link
1914 * java.util.regex.Pattern#matches(String,CharSequence)
1915 * matches}(</tt><i>regex</i><tt>,</tt> <i>str</i><tt>)</tt></blockquote>
1918 * the regular expression to which this string is to be matched
1920 * @return <tt>true</tt> if, and only if, this string matches the
1921 * given regular expression
1923 * @throws PatternSyntaxException
1924 * if the regular expression's syntax is invalid
1926 * @see java.util.regex.Pattern
1931 public boolean matches(String regex) {
1933 return matchesViaJS(regex);
1934 } catch (Throwable t) {
1935 // fallback to classical behavior
1937 Method m = Class.forName("java.util.regex.Pattern").getMethod("matches", String.class, CharSequence.class);
1938 return (Boolean)m.invoke(null, regex, this);
1939 } catch (InvocationTargetException ex) {
1940 if (ex.getTargetException() instanceof RuntimeException) {
1941 throw (RuntimeException)ex.getTargetException();
1943 } catch (Throwable another) {
1944 // will report the old one
1946 throw new RuntimeException(t);
1949 @JavaScriptBody(args = { "regex" }, body =
1950 "var self = this.toString();\n"
1951 + "var re = new RegExp(regex.toString());\n"
1952 + "var r = re.exec(self);\n"
1953 + "return r != null && r.length > 0 && self.length == r[0].length;"
1955 private boolean matchesViaJS(String regex) {
1956 throw new UnsupportedOperationException();
1960 * Returns true if and only if this string contains the specified
1961 * sequence of char values.
1963 * @param s the sequence to search for
1964 * @return true if this string contains <code>s</code>, false otherwise
1965 * @throws NullPointerException if <code>s</code> is <code>null</code>
1968 public boolean contains(CharSequence s) {
1969 return indexOf(s.toString()) > -1;
1973 * Replaces the first substring of this string that matches the given <a
1974 * href="../util/regex/Pattern.html#sum">regular expression</a> with the
1975 * given replacement.
1977 * <p> An invocation of this method of the form
1978 * <i>str</i><tt>.replaceFirst(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt>
1979 * yields exactly the same result as the expression
1982 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
1983 * compile}(</tt><i>regex</i><tt>).{@link
1984 * java.util.regex.Pattern#matcher(java.lang.CharSequence)
1985 * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceFirst
1986 * replaceFirst}(</tt><i>repl</i><tt>)</tt></blockquote>
1989 * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the
1990 * replacement string may cause the results to be different than if it were
1991 * being treated as a literal replacement string; see
1992 * {@link java.util.regex.Matcher#replaceFirst}.
1993 * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
1994 * meaning of these characters, if desired.
1997 * the regular expression to which this string is to be matched
1998 * @param replacement
1999 * the string to be substituted for the first match
2001 * @return The resulting <tt>String</tt>
2003 * @throws PatternSyntaxException
2004 * if the regular expression's syntax is invalid
2006 * @see java.util.regex.Pattern
2011 @JavaScriptBody(args = { "regex", "newText" }, body =
2012 "var self = this.toString();\n"
2013 + "var re = new RegExp(regex.toString());\n"
2014 + "var r = re.exec(self);\n"
2015 + "if (r === null || r.length === 0) return this;\n"
2016 + "var from = self.indexOf(r[0]);\n"
2017 + "return this.substring(0, from) + newText + this.substring(from + r[0].length);\n"
2019 public String replaceFirst(String regex, String replacement) {
2020 throw new UnsupportedOperationException();
2024 * Replaces each substring of this string that matches the given <a
2025 * href="../util/regex/Pattern.html#sum">regular expression</a> with the
2026 * given replacement.
2028 * <p> An invocation of this method of the form
2029 * <i>str</i><tt>.replaceAll(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt>
2030 * yields exactly the same result as the expression
2033 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2034 * compile}(</tt><i>regex</i><tt>).{@link
2035 * java.util.regex.Pattern#matcher(java.lang.CharSequence)
2036 * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceAll
2037 * replaceAll}(</tt><i>repl</i><tt>)</tt></blockquote>
2040 * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the
2041 * replacement string may cause the results to be different than if it were
2042 * being treated as a literal replacement string; see
2043 * {@link java.util.regex.Matcher#replaceAll Matcher.replaceAll}.
2044 * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
2045 * meaning of these characters, if desired.
2048 * the regular expression to which this string is to be matched
2049 * @param replacement
2050 * the string to be substituted for each match
2052 * @return The resulting <tt>String</tt>
2054 * @throws PatternSyntaxException
2055 * if the regular expression's syntax is invalid
2057 * @see java.util.regex.Pattern
2062 public String replaceAll(String regex, String replacement) {
2065 String n = p.replaceFirst(regex, replacement);
2074 * Replaces each substring of this string that matches the literal target
2075 * sequence with the specified literal replacement sequence. The
2076 * replacement proceeds from the beginning of the string to the end, for
2077 * example, replacing "aa" with "b" in the string "aaa" will result in
2078 * "ba" rather than "ab".
2080 * @param target The sequence of char values to be replaced
2081 * @param replacement The replacement sequence of char values
2082 * @return The resulting string
2083 * @throws NullPointerException if <code>target</code> or
2084 * <code>replacement</code> is <code>null</code>.
2087 @JavaScriptBody(args = { "target", "replacement" }, body =
2088 "var s = this.toString();\n"
2089 + "target = target.toString();\n"
2090 + "replacement = replacement.toString();\n"
2093 + " var indx = s.indexOf(target, pos);\n"
2094 + " if (indx === -1) {\n"
2097 + " pos = indx + replacement.length;\n"
2098 + " s = s.substring(0, indx) + replacement + s.substring(indx + target.length);\n"
2101 public native String replace(CharSequence target, CharSequence replacement);
2104 * Splits this string around matches of the given
2105 * <a href="../util/regex/Pattern.html#sum">regular expression</a>.
2107 * <p> The array returned by this method contains each substring of this
2108 * string that is terminated by another substring that matches the given
2109 * expression or is terminated by the end of the string. The substrings in
2110 * the array are in the order in which they occur in this string. If the
2111 * expression does not match any part of the input then the resulting array
2112 * has just one element, namely this string.
2114 * <p> The <tt>limit</tt> parameter controls the number of times the
2115 * pattern is applied and therefore affects the length of the resulting
2116 * array. If the limit <i>n</i> is greater than zero then the pattern
2117 * will be applied at most <i>n</i> - 1 times, the array's
2118 * length will be no greater than <i>n</i>, and the array's last entry
2119 * will contain all input beyond the last matched delimiter. If <i>n</i>
2120 * is non-positive then the pattern will be applied as many times as
2121 * possible and the array can have any length. If <i>n</i> is zero then
2122 * the pattern will be applied as many times as possible, the array can
2123 * have any length, and trailing empty strings will be discarded.
2125 * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the
2126 * following results with these parameters:
2128 * <blockquote><table cellpadding=1 cellspacing=0 summary="Split example showing regex, limit, and result">
2134 * <tr><td align=center>:</td>
2135 * <td align=center>2</td>
2136 * <td><tt>{ "boo", "and:foo" }</tt></td></tr>
2137 * <tr><td align=center>:</td>
2138 * <td align=center>5</td>
2139 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2140 * <tr><td align=center>:</td>
2141 * <td align=center>-2</td>
2142 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2143 * <tr><td align=center>o</td>
2144 * <td align=center>5</td>
2145 * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
2146 * <tr><td align=center>o</td>
2147 * <td align=center>-2</td>
2148 * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
2149 * <tr><td align=center>o</td>
2150 * <td align=center>0</td>
2151 * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
2152 * </table></blockquote>
2154 * <p> An invocation of this method of the form
2155 * <i>str.</i><tt>split(</tt><i>regex</i><tt>,</tt> <i>n</i><tt>)</tt>
2156 * yields the same result as the expression
2159 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2160 * compile}<tt>(</tt><i>regex</i><tt>)</tt>.{@link
2161 * java.util.regex.Pattern#split(java.lang.CharSequence,int)
2162 * split}<tt>(</tt><i>str</i><tt>,</tt> <i>n</i><tt>)</tt>
2167 * the delimiting regular expression
2170 * the result threshold, as described above
2172 * @return the array of strings computed by splitting this string
2173 * around matches of the given regular expression
2175 * @throws PatternSyntaxException
2176 * if the regular expression's syntax is invalid
2178 * @see java.util.regex.Pattern
2183 public String[] split(String regex, int limit) {
2185 Object[] arr = splitImpl(this, regex, Integer.MAX_VALUE);
2186 int to = arr.length;
2187 if (limit == 0 && to > 0) {
2188 while (to > 0 && ((String)arr[--to]).isEmpty()) {
2192 String[] ret = new String[to];
2193 System.arraycopy(arr, 0, ret, 0, to);
2196 Object[] arr = splitImpl(this, regex, limit);
2197 String[] ret = new String[arr.length];
2199 for (int i = 0; i < arr.length; i++) {
2200 final String s = (String)arr[i];
2202 pos = indexOf(s, pos) + s.length();
2204 ret[arr.length - 1] += substring(pos);
2209 @JavaScriptBody(args = { "str", "regex", "limit"}, body =
2210 "return str.split(new RegExp(regex), limit);"
2212 private static native Object[] splitImpl(String str, String regex, int limit);
2215 * Splits this string around matches of the given <a
2216 * href="../util/regex/Pattern.html#sum">regular expression</a>.
2218 * <p> This method works as if by invoking the two-argument {@link
2219 * #split(String, int) split} method with the given expression and a limit
2220 * argument of zero. Trailing empty strings are therefore not included in
2221 * the resulting array.
2223 * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the following
2224 * results with these expressions:
2226 * <blockquote><table cellpadding=1 cellspacing=0 summary="Split examples showing regex and result">
2231 * <tr><td align=center>:</td>
2232 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2233 * <tr><td align=center>o</td>
2234 * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
2235 * </table></blockquote>
2239 * the delimiting regular expression
2241 * @return the array of strings computed by splitting this string
2242 * around matches of the given regular expression
2244 * @throws PatternSyntaxException
2245 * if the regular expression's syntax is invalid
2247 * @see java.util.regex.Pattern
2252 public String[] split(String regex) {
2253 return split(regex, 0);
2257 * Converts all of the characters in this <code>String</code> to lower
2258 * case using the rules of the given <code>Locale</code>. Case mapping is based
2259 * on the Unicode Standard version specified by the {@link java.lang.Character Character}
2260 * class. Since case mappings are not always 1:1 char mappings, the resulting
2261 * <code>String</code> may be a different length than the original <code>String</code>.
2263 * Examples of lowercase mappings are in the following table:
2264 * <table border="1" summary="Lowercase mapping examples showing language code of locale, upper case, lower case, and description">
2266 * <th>Language Code of Locale</th>
2267 * <th>Upper Case</th>
2268 * <th>Lower Case</th>
2269 * <th>Description</th>
2272 * <td>tr (Turkish)</td>
2273 * <td>\u0130</td>
2274 * <td>\u0069</td>
2275 * <td>capital letter I with dot above -> small letter i</td>
2278 * <td>tr (Turkish)</td>
2279 * <td>\u0049</td>
2280 * <td>\u0131</td>
2281 * <td>capital letter I -> small letter dotless i </td>
2285 * <td>French Fries</td>
2286 * <td>french fries</td>
2287 * <td>lowercased all chars in String</td>
2291 * <td><img src="doc-files/capiota.gif" alt="capiota"><img src="doc-files/capchi.gif" alt="capchi">
2292 * <img src="doc-files/captheta.gif" alt="captheta"><img src="doc-files/capupsil.gif" alt="capupsil">
2293 * <img src="doc-files/capsigma.gif" alt="capsigma"></td>
2294 * <td><img src="doc-files/iota.gif" alt="iota"><img src="doc-files/chi.gif" alt="chi">
2295 * <img src="doc-files/theta.gif" alt="theta"><img src="doc-files/upsilon.gif" alt="upsilon">
2296 * <img src="doc-files/sigma1.gif" alt="sigma"></td>
2297 * <td>lowercased all chars in String</td>
2301 * @param locale use the case transformation rules for this locale
2302 * @return the <code>String</code>, converted to lowercase.
2303 * @see java.lang.String#toLowerCase()
2304 * @see java.lang.String#toUpperCase()
2305 * @see java.lang.String#toUpperCase(Locale)
2308 public String toLowerCase(java.util.Locale locale) {
2309 return toLowerCase();
2311 // if (locale == null) {
2312 // throw new NullPointerException();
2317 // /* Now check if there are any characters that need to be changed. */
2319 // for (firstUpper = 0 ; firstUpper < count; ) {
2320 // char c = value[offset+firstUpper];
2321 // if ((c >= Character.MIN_HIGH_SURROGATE) &&
2322 // (c <= Character.MAX_HIGH_SURROGATE)) {
2323 // int supplChar = codePointAt(firstUpper);
2324 // if (supplChar != Character.toLowerCase(supplChar)) {
2327 // firstUpper += Character.charCount(supplChar);
2329 // if (c != Character.toLowerCase(c)) {
2338 // char[] result = new char[count];
2339 // int resultOffset = 0; /* result may grow, so i+resultOffset
2340 // * is the write location in result */
2342 // /* Just copy the first few lowerCase characters. */
2343 // System.arraycopy(value, offset, result, 0, firstUpper);
2345 // String lang = locale.getLanguage();
2346 // boolean localeDependent =
2347 // (lang == "tr" || lang == "az" || lang == "lt");
2348 // char[] lowerCharArray;
2352 // for (int i = firstUpper; i < count; i += srcCount) {
2353 // srcChar = (int)value[offset+i];
2354 // if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
2355 // (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
2356 // srcChar = codePointAt(i);
2357 // srcCount = Character.charCount(srcChar);
2361 // if (localeDependent || srcChar == '\u03A3') { // GREEK CAPITAL LETTER SIGMA
2362 // lowerChar = ConditionalSpecialCasing.toLowerCaseEx(this, i, locale);
2363 // } else if (srcChar == '\u0130') { // LATIN CAPITAL LETTER I DOT
2364 // lowerChar = Character.ERROR;
2366 // lowerChar = Character.toLowerCase(srcChar);
2368 // if ((lowerChar == Character.ERROR) ||
2369 // (lowerChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
2370 // if (lowerChar == Character.ERROR) {
2371 // if (!localeDependent && srcChar == '\u0130') {
2373 // ConditionalSpecialCasing.toLowerCaseCharArray(this, i, Locale.ENGLISH);
2376 // ConditionalSpecialCasing.toLowerCaseCharArray(this, i, locale);
2378 // } else if (srcCount == 2) {
2379 // resultOffset += Character.toChars(lowerChar, result, i + resultOffset) - srcCount;
2382 // lowerCharArray = Character.toChars(lowerChar);
2385 // /* Grow result if needed */
2386 // int mapLen = lowerCharArray.length;
2387 // if (mapLen > srcCount) {
2388 // char[] result2 = new char[result.length + mapLen - srcCount];
2389 // System.arraycopy(result, 0, result2, 0,
2390 // i + resultOffset);
2391 // result = result2;
2393 // for (int x=0; x<mapLen; ++x) {
2394 // result[i+resultOffset+x] = lowerCharArray[x];
2396 // resultOffset += (mapLen - srcCount);
2398 // result[i+resultOffset] = (char)lowerChar;
2401 // return new String(0, count+resultOffset, result);
2405 * Converts all of the characters in this <code>String</code> to lower
2406 * case using the rules of the default locale. This is equivalent to calling
2407 * <code>toLowerCase(Locale.getDefault())</code>.
2409 * <b>Note:</b> This method is locale sensitive, and may produce unexpected
2410 * results if used for strings that are intended to be interpreted locale
2412 * Examples are programming language identifiers, protocol keys, and HTML
2414 * For instance, <code>"TITLE".toLowerCase()</code> in a Turkish locale
2415 * returns <code>"t\u005Cu0131tle"</code>, where '\u005Cu0131' is the
2416 * LATIN SMALL LETTER DOTLESS I character.
2417 * To obtain correct results for locale insensitive strings, use
2418 * <code>toLowerCase(Locale.ENGLISH)</code>.
2420 * @return the <code>String</code>, converted to lowercase.
2421 * @see java.lang.String#toLowerCase(Locale)
2423 @JavaScriptBody(args = {}, body = "return this.toLowerCase();")
2424 public String toLowerCase() {
2429 * Converts all of the characters in this <code>String</code> to upper
2430 * case using the rules of the given <code>Locale</code>. Case mapping is based
2431 * on the Unicode Standard version specified by the {@link java.lang.Character Character}
2432 * class. Since case mappings are not always 1:1 char mappings, the resulting
2433 * <code>String</code> may be a different length than the original <code>String</code>.
2435 * Examples of locale-sensitive and 1:M case mappings are in the following table.
2437 * <table border="1" summary="Examples of locale-sensitive and 1:M case mappings. Shows Language code of locale, lower case, upper case, and description.">
2439 * <th>Language Code of Locale</th>
2440 * <th>Lower Case</th>
2441 * <th>Upper Case</th>
2442 * <th>Description</th>
2445 * <td>tr (Turkish)</td>
2446 * <td>\u0069</td>
2447 * <td>\u0130</td>
2448 * <td>small letter i -> capital letter I with dot above</td>
2451 * <td>tr (Turkish)</td>
2452 * <td>\u0131</td>
2453 * <td>\u0049</td>
2454 * <td>small letter dotless i -> capital letter I</td>
2458 * <td>\u00df</td>
2459 * <td>\u0053 \u0053</td>
2460 * <td>small letter sharp s -> two letters: SS</td>
2464 * <td>Fahrvergnügen</td>
2465 * <td>FAHRVERGNÜGEN</td>
2469 * @param locale use the case transformation rules for this locale
2470 * @return the <code>String</code>, converted to uppercase.
2471 * @see java.lang.String#toUpperCase()
2472 * @see java.lang.String#toLowerCase()
2473 * @see java.lang.String#toLowerCase(Locale)
2476 public String toUpperCase(Locale locale) {
2477 return toUpperCase();
2479 /* not for javascript
2480 if (locale == null) {
2481 throw new NullPointerException();
2486 // Now check if there are any characters that need to be changed.
2488 for (firstLower = 0 ; firstLower < count; ) {
2489 int c = (int)value[offset+firstLower];
2491 if ((c >= Character.MIN_HIGH_SURROGATE) &&
2492 (c <= Character.MAX_HIGH_SURROGATE)) {
2493 c = codePointAt(firstLower);
2494 srcCount = Character.charCount(c);
2498 int upperCaseChar = Character.toUpperCaseEx(c);
2499 if ((upperCaseChar == Character.ERROR) ||
2500 (c != upperCaseChar)) {
2503 firstLower += srcCount;
2508 char[] result = new char[count]; /* may grow *
2509 int resultOffset = 0; /* result may grow, so i+resultOffset
2510 * is the write location in result *
2512 /* Just copy the first few upperCase characters. *
2513 System.arraycopy(value, offset, result, 0, firstLower);
2515 String lang = locale.getLanguage();
2516 boolean localeDependent =
2517 (lang == "tr" || lang == "az" || lang == "lt");
2518 char[] upperCharArray;
2522 for (int i = firstLower; i < count; i += srcCount) {
2523 srcChar = (int)value[offset+i];
2524 if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
2525 (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
2526 srcChar = codePointAt(i);
2527 srcCount = Character.charCount(srcChar);
2531 if (localeDependent) {
2532 upperChar = ConditionalSpecialCasing.toUpperCaseEx(this, i, locale);
2534 upperChar = Character.toUpperCaseEx(srcChar);
2536 if ((upperChar == Character.ERROR) ||
2537 (upperChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
2538 if (upperChar == Character.ERROR) {
2539 if (localeDependent) {
2541 ConditionalSpecialCasing.toUpperCaseCharArray(this, i, locale);
2543 upperCharArray = Character.toUpperCaseCharArray(srcChar);
2545 } else if (srcCount == 2) {
2546 resultOffset += Character.toChars(upperChar, result, i + resultOffset) - srcCount;
2549 upperCharArray = Character.toChars(upperChar);
2552 /* Grow result if needed *
2553 int mapLen = upperCharArray.length;
2554 if (mapLen > srcCount) {
2555 char[] result2 = new char[result.length + mapLen - srcCount];
2556 System.arraycopy(result, 0, result2, 0,
2560 for (int x=0; x<mapLen; ++x) {
2561 result[i+resultOffset+x] = upperCharArray[x];
2563 resultOffset += (mapLen - srcCount);
2565 result[i+resultOffset] = (char)upperChar;
2568 return new String(0, count+resultOffset, result);
2573 * Converts all of the characters in this <code>String</code> to upper
2574 * case using the rules of the default locale. This method is equivalent to
2575 * <code>toUpperCase(Locale.getDefault())</code>.
2577 * <b>Note:</b> This method is locale sensitive, and may produce unexpected
2578 * results if used for strings that are intended to be interpreted locale
2580 * Examples are programming language identifiers, protocol keys, and HTML
2582 * For instance, <code>"title".toUpperCase()</code> in a Turkish locale
2583 * returns <code>"T\u005Cu0130TLE"</code>, where '\u005Cu0130' is the
2584 * LATIN CAPITAL LETTER I WITH DOT ABOVE character.
2585 * To obtain correct results for locale insensitive strings, use
2586 * <code>toUpperCase(Locale.ENGLISH)</code>.
2588 * @return the <code>String</code>, converted to uppercase.
2589 * @see java.lang.String#toUpperCase(Locale)
2591 @JavaScriptBody(args = {}, body = "return this.toUpperCase();")
2592 public String toUpperCase() {
2597 * Returns a copy of the string, with leading and trailing whitespace
2600 * If this <code>String</code> object represents an empty character
2601 * sequence, or the first and last characters of character sequence
2602 * represented by this <code>String</code> object both have codes
2603 * greater than <code>'\u0020'</code> (the space character), then a
2604 * reference to this <code>String</code> object is returned.
2606 * Otherwise, if there is no character with a code greater than
2607 * <code>'\u0020'</code> in the string, then a new
2608 * <code>String</code> object representing an empty string is created
2611 * Otherwise, let <i>k</i> be the index of the first character in the
2612 * string whose code is greater than <code>'\u0020'</code>, and let
2613 * <i>m</i> be the index of the last character in the string whose code
2614 * is greater than <code>'\u0020'</code>. A new <code>String</code>
2615 * object is created, representing the substring of this string that
2616 * begins with the character at index <i>k</i> and ends with the
2617 * character at index <i>m</i>-that is, the result of
2618 * <code>this.substring(<i>k</i>, <i>m</i>+1)</code>.
2620 * This method may be used to trim whitespace (as defined above) from
2621 * the beginning and end of a string.
2623 * @return A copy of this string with leading and trailing white
2624 * space removed, or this string if it has no leading or
2625 * trailing white space.
2627 public String trim() {
2630 int off = offset(); /* avoid getfield opcode */
2632 while ((st < len) && (this.charAt(off + st) <= ' ')) {
2635 while ((st < len) && (this.charAt(off + len - 1) <= ' ')) {
2638 return ((st > 0) || (len < length())) ? substring(st, len) : this;
2642 * This object (which is already a string!) is itself returned.
2644 * @return the string itself.
2646 @JavaScriptBody(args = {}, body = "return this.toString();")
2647 public String toString() {
2652 * Converts this string to a new character array.
2654 * @return a newly allocated character array whose length is the length
2655 * of this string and whose contents are initialized to contain
2656 * the character sequence represented by this string.
2658 public char[] toCharArray() {
2659 char result[] = new char[length()];
2660 getChars(0, length(), result, 0);
2665 * Returns a formatted string using the specified format string and
2668 * <p> The locale always used is the one returned by {@link
2669 * java.util.Locale#getDefault() Locale.getDefault()}.
2672 * A <a href="../util/Formatter.html#syntax">format string</a>
2675 * Arguments referenced by the format specifiers in the format
2676 * string. If there are more arguments than format specifiers, the
2677 * extra arguments are ignored. The number of arguments is
2678 * variable and may be zero. The maximum number of arguments is
2679 * limited by the maximum dimension of a Java array as defined by
2680 * <cite>The Java™ Virtual Machine Specification</cite>.
2681 * The behaviour on a
2682 * <tt>null</tt> argument depends on the <a
2683 * href="../util/Formatter.html#syntax">conversion</a>.
2685 * @throws IllegalFormatException
2686 * If a format string contains an illegal syntax, a format
2687 * specifier that is incompatible with the given arguments,
2688 * insufficient arguments given the format string, or other
2689 * illegal conditions. For specification of all possible
2690 * formatting errors, see the <a
2691 * href="../util/Formatter.html#detail">Details</a> section of the
2692 * formatter class specification.
2694 * @throws NullPointerException
2695 * If the <tt>format</tt> is <tt>null</tt>
2697 * @return A formatted string
2699 * @see java.util.Formatter
2702 public static String format(String format, Object ... args) {
2703 return format((Locale)null, format, args);
2707 * Returns a formatted string using the specified locale, format string,
2711 * The {@linkplain java.util.Locale locale} to apply during
2712 * formatting. If <tt>l</tt> is <tt>null</tt> then no localization
2716 * A <a href="../util/Formatter.html#syntax">format string</a>
2719 * Arguments referenced by the format specifiers in the format
2720 * string. If there are more arguments than format specifiers, the
2721 * extra arguments are ignored. The number of arguments is
2722 * variable and may be zero. The maximum number of arguments is
2723 * limited by the maximum dimension of a Java array as defined by
2724 * <cite>The Java™ Virtual Machine Specification</cite>.
2725 * The behaviour on a
2726 * <tt>null</tt> argument depends on the <a
2727 * href="../util/Formatter.html#syntax">conversion</a>.
2729 * @throws IllegalFormatException
2730 * If a format string contains an illegal syntax, a format
2731 * specifier that is incompatible with the given arguments,
2732 * insufficient arguments given the format string, or other
2733 * illegal conditions. For specification of all possible
2734 * formatting errors, see the <a
2735 * href="../util/Formatter.html#detail">Details</a> section of the
2736 * formatter class specification
2738 * @throws NullPointerException
2739 * If the <tt>format</tt> is <tt>null</tt>
2741 * @return A formatted string
2743 * @see java.util.Formatter
2746 public static String format(Locale l, String format, Object ... args) {
2748 for (int i = 0; i < args.length; i++) {
2749 String v = args[i] == null ? "null" : args[i].toString();
2750 p = p.replaceFirst("%s", v);
2753 // return new Formatter(l).format(format, args).toString();
2757 * Returns the string representation of the <code>Object</code> argument.
2759 * @param obj an <code>Object</code>.
2760 * @return if the argument is <code>null</code>, then a string equal to
2761 * <code>"null"</code>; otherwise, the value of
2762 * <code>obj.toString()</code> is returned.
2763 * @see java.lang.Object#toString()
2765 public static String valueOf(Object obj) {
2766 return (obj == null) ? "null" : obj.toString();
2770 * Returns the string representation of the <code>char</code> array
2771 * argument. The contents of the character array are copied; subsequent
2772 * modification of the character array does not affect the newly
2775 * @param data a <code>char</code> array.
2776 * @return a newly allocated string representing the same sequence of
2777 * characters contained in the character array argument.
2779 public static String valueOf(char data[]) {
2780 return new String(data);
2784 * Returns the string representation of a specific subarray of the
2785 * <code>char</code> array argument.
2787 * The <code>offset</code> argument is the index of the first
2788 * character of the subarray. The <code>count</code> argument
2789 * specifies the length of the subarray. The contents of the subarray
2790 * are copied; subsequent modification of the character array does not
2791 * affect the newly created string.
2793 * @param data the character array.
2794 * @param offset the initial offset into the value of the
2795 * <code>String</code>.
2796 * @param count the length of the value of the <code>String</code>.
2797 * @return a string representing the sequence of characters contained
2798 * in the subarray of the character array argument.
2799 * @exception IndexOutOfBoundsException if <code>offset</code> is
2800 * negative, or <code>count</code> is negative, or
2801 * <code>offset+count</code> is larger than
2802 * <code>data.length</code>.
2804 public static String valueOf(char data[], int offset, int count) {
2805 return new String(data, offset, count);
2809 * Returns a String that represents the character sequence in the
2812 * @param data the character array.
2813 * @param offset initial offset of the subarray.
2814 * @param count length of the subarray.
2815 * @return a <code>String</code> that contains the characters of the
2816 * specified subarray of the character array.
2818 public static String copyValueOf(char data[], int offset, int count) {
2819 // All public String constructors now copy the data.
2820 return new String(data, offset, count);
2824 * Returns a String that represents the character sequence in the
2827 * @param data the character array.
2828 * @return a <code>String</code> that contains the characters of the
2831 public static String copyValueOf(char data[]) {
2832 return copyValueOf(data, 0, data.length);
2836 * Returns the string representation of the <code>boolean</code> argument.
2838 * @param b a <code>boolean</code>.
2839 * @return if the argument is <code>true</code>, a string equal to
2840 * <code>"true"</code> is returned; otherwise, a string equal to
2841 * <code>"false"</code> is returned.
2843 public static String valueOf(boolean b) {
2844 return b ? "true" : "false";
2848 * Returns the string representation of the <code>char</code>
2851 * @param c a <code>char</code>.
2852 * @return a string of length <code>1</code> containing
2853 * as its single character the argument <code>c</code>.
2855 public static String valueOf(char c) {
2857 return new String(data, 0, 1);
2861 * Returns the string representation of the <code>int</code> argument.
2863 * The representation is exactly the one returned by the
2864 * <code>Integer.toString</code> method of one argument.
2866 * @param i an <code>int</code>.
2867 * @return a string representation of the <code>int</code> argument.
2868 * @see java.lang.Integer#toString(int, int)
2870 public static String valueOf(int i) {
2871 return Integer.toString(i);
2875 * Returns the string representation of the <code>long</code> argument.
2877 * The representation is exactly the one returned by the
2878 * <code>Long.toString</code> method of one argument.
2880 * @param l a <code>long</code>.
2881 * @return a string representation of the <code>long</code> argument.
2882 * @see java.lang.Long#toString(long)
2884 public static String valueOf(long l) {
2885 return Long.toString(l);
2889 * Returns the string representation of the <code>float</code> argument.
2891 * The representation is exactly the one returned by the
2892 * <code>Float.toString</code> method of one argument.
2894 * @param f a <code>float</code>.
2895 * @return a string representation of the <code>float</code> argument.
2896 * @see java.lang.Float#toString(float)
2898 public static String valueOf(float f) {
2899 return Float.toString(f);
2903 * Returns the string representation of the <code>double</code> argument.
2905 * The representation is exactly the one returned by the
2906 * <code>Double.toString</code> method of one argument.
2908 * @param d a <code>double</code>.
2909 * @return a string representation of the <code>double</code> argument.
2910 * @see java.lang.Double#toString(double)
2912 public static String valueOf(double d) {
2913 return Double.toString(d);
2917 * Returns a canonical representation for the string object.
2919 * A pool of strings, initially empty, is maintained privately by the
2920 * class <code>String</code>.
2922 * When the intern method is invoked, if the pool already contains a
2923 * string equal to this <code>String</code> object as determined by
2924 * the {@link #equals(Object)} method, then the string from the pool is
2925 * returned. Otherwise, this <code>String</code> object is added to the
2926 * pool and a reference to this <code>String</code> object is returned.
2928 * It follows that for any two strings <code>s</code> and <code>t</code>,
2929 * <code>s.intern() == t.intern()</code> is <code>true</code>
2930 * if and only if <code>s.equals(t)</code> is <code>true</code>.
2932 * All literal strings and string-valued constant expressions are
2933 * interned. String literals are defined in section 3.10.5 of the
2934 * <cite>The Java™ Language Specification</cite>.
2936 * @return a string that has the same contents as this string, but is
2937 * guaranteed to be from a pool of unique strings.
2939 @JavaScriptBody(args = {}, body =
2940 "var s = this.toString().toString();\n" +
2941 "var i = String.intern || (String.intern = {})\n" +
2947 public native String intern();
2950 private static <T> T checkUTF8(T data, String charsetName)
2951 throws UnsupportedEncodingException {
2952 if (charsetName == null) {
2953 throw new NullPointerException("charsetName");
2955 if (!charsetName.equalsIgnoreCase("UTF-8")
2956 && !charsetName.equalsIgnoreCase("UTF8")) {
2957 throw new UnsupportedEncodingException(charsetName);
2962 private static int nextChar(byte[] arr, int[] index) throws IndexOutOfBoundsException {
2963 int c = arr[index[0]++] & 0xff;
2977 /* 110x xxxx 10xx xxxx*/
2978 int char2 = (int) arr[index[0]++];
2979 if ((char2 & 0xC0) != 0x80) {
2980 throw new IndexOutOfBoundsException("malformed input");
2982 return (((c & 0x1F) << 6) | (char2 & 0x3F));
2985 /* 1110 xxxx 10xx xxxx 10xx xxxx */
2986 int char2 = arr[index[0]++];
2987 int char3 = arr[index[0]++];
2988 if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80)) {
2989 throw new IndexOutOfBoundsException("malformed input");
2991 return (((c & 0x0F) << 12)
2992 | ((char2 & 0x3F) << 6)
2993 | ((char3 & 0x3F) << 0));
2996 /* 10xx xxxx, 1111 xxxx */
2997 throw new IndexOutOfBoundsException("malformed input");