2 * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
28 import java.io.UnsupportedEncodingException;
29 import java.util.Comparator;
30 import org.apidesign.bck2brwsr.core.ExtraJavaScript;
31 import org.apidesign.bck2brwsr.core.JavaScriptBody;
32 import org.apidesign.bck2brwsr.core.JavaScriptOnly;
33 import org.apidesign.bck2brwsr.core.JavaScriptPrototype;
34 import org.apidesign.bck2brwsr.emul.lang.System;
37 * The <code>String</code> class represents character strings. All
38 * string literals in Java programs, such as <code>"abc"</code>, are
39 * implemented as instances of this class.
41 * Strings are constant; their values cannot be changed after they
42 * are created. String buffers support mutable strings.
43 * Because String objects are immutable they can be shared. For example:
44 * <p><blockquote><pre>
46 * </pre></blockquote><p>
48 * <p><blockquote><pre>
49 * char data[] = {'a', 'b', 'c'};
50 * String str = new String(data);
51 * </pre></blockquote><p>
52 * Here are some more examples of how strings can be used:
53 * <p><blockquote><pre>
54 * System.out.println("abc");
56 * System.out.println("abc" + cde);
57 * String c = "abc".substring(2,3);
58 * String d = cde.substring(1, 2);
61 * The class <code>String</code> includes methods for examining
62 * individual characters of the sequence, for comparing strings, for
63 * searching strings, for extracting substrings, and for creating a
64 * copy of a string with all characters translated to uppercase or to
65 * lowercase. Case mapping is based on the Unicode Standard version
66 * specified by the {@link java.lang.Character Character} class.
68 * The Java language provides special support for the string
69 * concatenation operator ( + ), and for conversion of
70 * other objects to strings. String concatenation is implemented
71 * through the <code>StringBuilder</code>(or <code>StringBuffer</code>)
72 * class and its <code>append</code> method.
73 * String conversions are implemented through the method
74 * <code>toString</code>, defined by <code>Object</code> and
75 * inherited by all classes in Java. For additional information on
76 * string concatenation and conversion, see Gosling, Joy, and Steele,
77 * <i>The Java Language Specification</i>.
79 * <p> Unless otherwise noted, passing a <tt>null</tt> argument to a constructor
80 * or method in this class will cause a {@link NullPointerException} to be
83 * <p>A <code>String</code> represents a string in the UTF-16 format
84 * in which <em>supplementary characters</em> are represented by <em>surrogate
85 * pairs</em> (see the section <a href="Character.html#unicode">Unicode
86 * Character Representations</a> in the <code>Character</code> class for
88 * Index values refer to <code>char</code> code units, so a supplementary
89 * character uses two positions in a <code>String</code>.
90 * <p>The <code>String</code> class provides methods for dealing with
91 * Unicode code points (i.e., characters), in addition to those for
92 * dealing with Unicode code units (i.e., <code>char</code> values).
95 * @author Arthur van Hoff
96 * @author Martin Buchholz
98 * @see java.lang.Object#toString()
99 * @see java.lang.StringBuffer
100 * @see java.lang.StringBuilder
101 * @see java.nio.charset.Charset
106 resource="/org/apidesign/vm4brwsr/emul/lang/java_lang_String.js",
109 @JavaScriptPrototype(container = "String.prototype", prototype = "new String")
110 public final class String
111 implements java.io.Serializable, Comparable<String>, CharSequence
113 /** real string to delegate to */
116 /** use serialVersionUID from JDK 1.0.2 for interoperability */
117 private static final long serialVersionUID = -6849794470754667710L;
119 @JavaScriptOnly(name="toString", value="String.prototype._r")
120 private static void jsToString() {
123 @JavaScriptOnly(name="valueOf", value="function() { return this.toString().valueOf(); }")
124 private static void jsValudOf() {
128 * Class String is special cased within the Serialization Stream Protocol.
130 * A String instance is written initially into an ObjectOutputStream in the
133 * <code>TC_STRING</code> (utf String)
135 * The String is written by method <code>DataOutput.writeUTF</code>.
136 * A new handle is generated to refer to all future references to the
137 * string instance within the stream.
139 // private static final ObjectStreamField[] serialPersistentFields =
140 // new ObjectStreamField[0];
143 * Initializes a newly created {@code String} object so that it represents
144 * an empty character sequence. Note that use of this constructor is
145 * unnecessary since Strings are immutable.
152 * Initializes a newly created {@code String} object so that it represents
153 * the same sequence of characters as the argument; in other words, the
154 * newly created string is a copy of the argument string. Unless an
155 * explicit copy of {@code original} is needed, use of this constructor is
156 * unnecessary since Strings are immutable.
161 public String(String original) {
162 this.r = original.toString();
166 * Allocates a new {@code String} so that it represents the sequence of
167 * characters currently contained in the character array argument. The
168 * contents of the character array are copied; subsequent modification of
169 * the character array does not affect the newly created string.
172 * The initial value of the string
174 @JavaScriptBody(args = { "charArr" }, body=
175 "for (var i = 0; i < charArr.length; i++) {\n"
176 + " if (typeof charArr[i] === 'number') charArr[i] = String.fromCharCode(charArr[i]);\n"
178 + "this._r(charArr.join(''));\n"
180 public String(char value[]) {
184 * Allocates a new {@code String} that contains characters from a subarray
185 * of the character array argument. The {@code offset} argument is the
186 * index of the first character of the subarray and the {@code count}
187 * argument specifies the length of the subarray. The contents of the
188 * subarray are copied; subsequent modification of the character array does
189 * not affect the newly created string.
192 * Array that is the source of characters
200 * @throws IndexOutOfBoundsException
201 * If the {@code offset} and {@code count} arguments index
202 * characters outside the bounds of the {@code value} array
204 @JavaScriptBody(args = { "charArr", "off", "cnt" }, body =
205 "var up = off + cnt;\n" +
206 "for (var i = off; i < up; i++) {\n" +
207 " if (typeof charArr[i] === 'number') charArr[i] = String.fromCharCode(charArr[i]);\n" +
209 "this._r(charArr.slice(off, up).join(\"\"));\n"
211 public String(char value[], int offset, int count) {
215 * Allocates a new {@code String} that contains characters from a subarray
216 * of the <a href="Character.html#unicode">Unicode code point</a> array
217 * argument. The {@code offset} argument is the index of the first code
218 * point of the subarray and the {@code count} argument specifies the
219 * length of the subarray. The contents of the subarray are converted to
220 * {@code char}s; subsequent modification of the {@code int} array does not
221 * affect the newly created string.
224 * Array that is the source of Unicode code points
232 * @throws IllegalArgumentException
233 * If any invalid Unicode code point is found in {@code
236 * @throws IndexOutOfBoundsException
237 * If the {@code offset} and {@code count} arguments index
238 * characters outside the bounds of the {@code codePoints} array
242 public String(int[] codePoints, int offset, int count) {
244 throw new StringIndexOutOfBoundsException(offset);
247 throw new StringIndexOutOfBoundsException(count);
249 // Note: offset or count might be near -1>>>1.
250 if (offset > codePoints.length - count) {
251 throw new StringIndexOutOfBoundsException(offset + count);
254 final int end = offset + count;
256 // Pass 1: Compute precise size of char[]
258 for (int i = offset; i < end; i++) {
259 int c = codePoints[i];
260 if (Character.isBmpCodePoint(c))
262 else if (Character.isValidCodePoint(c))
264 else throw new IllegalArgumentException(Integer.toString(c));
267 // Pass 2: Allocate and fill in char[]
268 final char[] v = new char[n];
270 for (int i = offset, j = 0; i < end; i++, j++) {
271 int c = codePoints[i];
272 if (Character.isBmpCodePoint(c))
275 Character.toSurrogates(c, v, j++);
278 this.r = new String(v, 0, n);
282 * Allocates a new {@code String} constructed from a subarray of an array
283 * of 8-bit integer values.
285 * <p> The {@code offset} argument is the index of the first byte of the
286 * subarray, and the {@code count} argument specifies the length of the
289 * <p> Each {@code byte} in the subarray is converted to a {@code char} as
290 * specified in the method above.
292 * @deprecated This method does not properly convert bytes into characters.
293 * As of JDK 1.1, the preferred way to do this is via the
294 * {@code String} constructors that take a {@link
295 * java.nio.charset.Charset}, charset name, or that use the platform's
299 * The bytes to be converted to characters
302 * The top 8 bits of each 16-bit Unicode code unit
309 * @throws IndexOutOfBoundsException
310 * If the {@code offset} or {@code count} argument is invalid
312 * @see #String(byte[], int)
313 * @see #String(byte[], int, int, java.lang.String)
314 * @see #String(byte[], int, int, java.nio.charset.Charset)
315 * @see #String(byte[], int, int)
316 * @see #String(byte[], java.lang.String)
317 * @see #String(byte[], java.nio.charset.Charset)
318 * @see #String(byte[])
321 public String(byte ascii[], int hibyte, int offset, int count) {
322 checkBounds(ascii, offset, count);
323 char value[] = new char[count];
326 for (int i = count ; i-- > 0 ;) {
327 value[i] = (char) (ascii[i + offset] & 0xff);
331 for (int i = count ; i-- > 0 ;) {
332 value[i] = (char) (hibyte | (ascii[i + offset] & 0xff));
335 this.r = new String(value, 0, count);
339 * Allocates a new {@code String} containing characters constructed from
340 * an array of 8-bit integer values. Each character <i>c</i>in the
341 * resulting string is constructed from the corresponding component
342 * <i>b</i> in the byte array such that:
345 * <b><i>c</i></b> == (char)(((hibyte & 0xff) << 8)
346 * | (<b><i>b</i></b> & 0xff))
347 * </pre></blockquote>
349 * @deprecated This method does not properly convert bytes into
350 * characters. As of JDK 1.1, the preferred way to do this is via the
351 * {@code String} constructors that take a {@link
352 * java.nio.charset.Charset}, charset name, or that use the platform's
356 * The bytes to be converted to characters
359 * The top 8 bits of each 16-bit Unicode code unit
361 * @see #String(byte[], int, int, java.lang.String)
362 * @see #String(byte[], int, int, java.nio.charset.Charset)
363 * @see #String(byte[], int, int)
364 * @see #String(byte[], java.lang.String)
365 * @see #String(byte[], java.nio.charset.Charset)
366 * @see #String(byte[])
369 public String(byte ascii[], int hibyte) {
370 this(ascii, hibyte, 0, ascii.length);
373 /* Common private utility method used to bounds check the byte array
374 * and requested offset & length values used by the String(byte[],..)
377 private static void checkBounds(byte[] bytes, int offset, int length) {
379 throw new StringIndexOutOfBoundsException(length);
381 throw new StringIndexOutOfBoundsException(offset);
382 if (offset > bytes.length - length)
383 throw new StringIndexOutOfBoundsException(offset + length);
387 * Constructs a new {@code String} by decoding the specified subarray of
388 * bytes using the specified charset. The length of the new {@code String}
389 * is a function of the charset, and hence may not be equal to the length
392 * <p> The behavior of this constructor when the given bytes are not valid
393 * in the given charset is unspecified. The {@link
394 * java.nio.charset.CharsetDecoder} class should be used when more control
395 * over the decoding process is required.
398 * The bytes to be decoded into characters
401 * The index of the first byte to decode
404 * The number of bytes to decode
407 * The name of a supported {@linkplain java.nio.charset.Charset
410 * @throws UnsupportedEncodingException
411 * If the named charset is not supported
413 * @throws IndexOutOfBoundsException
414 * If the {@code offset} and {@code length} arguments index
415 * characters outside the bounds of the {@code bytes} array
419 public String(byte bytes[], int offset, int length, String charsetName)
420 throws UnsupportedEncodingException
422 this(checkUTF8(bytes, charsetName), offset, length);
426 * Constructs a new {@code String} by decoding the specified subarray of
427 * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
428 * The length of the new {@code String} is a function of the charset, and
429 * hence may not be equal to the length of the subarray.
431 * <p> This method always replaces malformed-input and unmappable-character
432 * sequences with this charset's default replacement string. The {@link
433 * java.nio.charset.CharsetDecoder} class should be used when more control
434 * over the decoding process is required.
437 * The bytes to be decoded into characters
440 * The index of the first byte to decode
443 * The number of bytes to decode
446 * The {@linkplain java.nio.charset.Charset charset} to be used to
447 * decode the {@code bytes}
449 * @throws IndexOutOfBoundsException
450 * If the {@code offset} and {@code length} arguments index
451 * characters outside the bounds of the {@code bytes} array
455 /* don't want dependnecy on Charset
456 public String(byte bytes[], int offset, int length, Charset charset) {
458 throw new NullPointerException("charset");
459 checkBounds(bytes, offset, length);
460 char[] v = StringCoding.decode(charset, bytes, offset, length);
462 this.count = v.length;
468 * Constructs a new {@code String} by decoding the specified array of bytes
469 * using the specified {@linkplain java.nio.charset.Charset charset}. The
470 * length of the new {@code String} is a function of the charset, and hence
471 * may not be equal to the length of the byte array.
473 * <p> The behavior of this constructor when the given bytes are not valid
474 * in the given charset is unspecified. The {@link
475 * java.nio.charset.CharsetDecoder} class should be used when more control
476 * over the decoding process is required.
479 * The bytes to be decoded into characters
482 * The name of a supported {@linkplain java.nio.charset.Charset
485 * @throws UnsupportedEncodingException
486 * If the named charset is not supported
490 public String(byte bytes[], String charsetName)
491 throws UnsupportedEncodingException
493 this(bytes, 0, bytes.length, charsetName);
497 * Constructs a new {@code String} by decoding the specified array of
498 * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
499 * The length of the new {@code String} is a function of the charset, and
500 * hence may not be equal to the length of the byte array.
502 * <p> This method always replaces malformed-input and unmappable-character
503 * sequences with this charset's default replacement string. The {@link
504 * java.nio.charset.CharsetDecoder} class should be used when more control
505 * over the decoding process is required.
508 * The bytes to be decoded into characters
511 * The {@linkplain java.nio.charset.Charset charset} to be used to
512 * decode the {@code bytes}
516 /* don't want dep on Charset
517 public String(byte bytes[], Charset charset) {
518 this(bytes, 0, bytes.length, charset);
523 * Constructs a new {@code String} by decoding the specified subarray of
524 * bytes using the platform's default charset. The length of the new
525 * {@code String} is a function of the charset, and hence may not be equal
526 * to the length of the subarray.
528 * <p> The behavior of this constructor when the given bytes are not valid
529 * in the default charset is unspecified. The {@link
530 * java.nio.charset.CharsetDecoder} class should be used when more control
531 * over the decoding process is required.
534 * The bytes to be decoded into characters
537 * The index of the first byte to decode
540 * The number of bytes to decode
542 * @throws IndexOutOfBoundsException
543 * If the {@code offset} and the {@code length} arguments index
544 * characters outside the bounds of the {@code bytes} array
548 public String(byte bytes[], int offset, int length) {
549 checkBounds(bytes, offset, length);
550 char[] v = new char[length];
551 int[] at = { offset };
552 int end = offset + length;
554 while (at[0] < end) {
555 int ch = nextChar(bytes, at);
556 v[chlen++] = (char)ch;
558 this.r = new String(v, 0, chlen);
562 * Constructs a new {@code String} by decoding the specified array of bytes
563 * using the platform's default charset. The length of the new {@code
564 * String} is a function of the charset, and hence may not be equal to the
565 * length of the byte array.
567 * <p> The behavior of this constructor when the given bytes are not valid
568 * in the default charset is unspecified. The {@link
569 * java.nio.charset.CharsetDecoder} class should be used when more control
570 * over the decoding process is required.
573 * The bytes to be decoded into characters
577 public String(byte bytes[]) {
578 this(bytes, 0, bytes.length);
582 * Allocates a new string that contains the sequence of characters
583 * currently contained in the string buffer argument. The contents of the
584 * string buffer are copied; subsequent modification of the string buffer
585 * does not affect the newly created string.
588 * A {@code StringBuffer}
590 public String(StringBuffer buffer) {
591 this.r = buffer.toString();
595 * Allocates a new string that contains the sequence of characters
596 * currently contained in the string builder argument. The contents of the
597 * string builder are copied; subsequent modification of the string builder
598 * does not affect the newly created string.
600 * <p> This constructor is provided to ease migration to {@code
601 * StringBuilder}. Obtaining a string from a string builder via the {@code
602 * toString} method is likely to run faster and is generally preferred.
605 * A {@code StringBuilder}
609 public String(StringBuilder builder) {
610 this.r = builder.toString();
614 * Returns the length of this string.
615 * The length is equal to the number of <a href="Character.html#unicode">Unicode
616 * code units</a> in the string.
618 * @return the length of the sequence of characters represented by this
621 @JavaScriptBody(args = {}, body = "return this.toString().length;")
622 public int length() {
623 throw new UnsupportedOperationException();
627 * Returns <tt>true</tt> if, and only if, {@link #length()} is <tt>0</tt>.
629 * @return <tt>true</tt> if {@link #length()} is <tt>0</tt>, otherwise
634 @JavaScriptBody(args = {}, body="return this.toString().length === 0;")
635 public boolean isEmpty() {
636 return length() == 0;
640 * Returns the <code>char</code> value at the
641 * specified index. An index ranges from <code>0</code> to
642 * <code>length() - 1</code>. The first <code>char</code> value of the sequence
643 * is at index <code>0</code>, the next at index <code>1</code>,
644 * and so on, as for array indexing.
646 * <p>If the <code>char</code> value specified by the index is a
647 * <a href="Character.html#unicode">surrogate</a>, the surrogate
650 * @param index the index of the <code>char</code> value.
651 * @return the <code>char</code> value at the specified index of this string.
652 * The first <code>char</code> value is at index <code>0</code>.
653 * @exception IndexOutOfBoundsException if the <code>index</code>
654 * argument is negative or not less than the length of this
657 @JavaScriptBody(args = { "index" },
658 body = "return this.toString().charCodeAt(index);"
660 public char charAt(int index) {
661 throw new UnsupportedOperationException();
665 * Returns the character (Unicode code point) at the specified
666 * index. The index refers to <code>char</code> values
667 * (Unicode code units) and ranges from <code>0</code> to
668 * {@link #length()}<code> - 1</code>.
670 * <p> If the <code>char</code> value specified at the given index
671 * is in the high-surrogate range, the following index is less
672 * than the length of this <code>String</code>, and the
673 * <code>char</code> value at the following index is in the
674 * low-surrogate range, then the supplementary code point
675 * corresponding to this surrogate pair is returned. Otherwise,
676 * the <code>char</code> value at the given index is returned.
678 * @param index the index to the <code>char</code> values
679 * @return the code point value of the character at the
681 * @exception IndexOutOfBoundsException if the <code>index</code>
682 * argument is negative or not less than the length of this
686 public int codePointAt(int index) {
687 if ((index < 0) || (index >= length())) {
688 throw new StringIndexOutOfBoundsException(index);
690 return Character.codePointAtImpl(toCharArray(), offset() + index, offset() + length());
694 * Returns the character (Unicode code point) before the specified
695 * index. The index refers to <code>char</code> values
696 * (Unicode code units) and ranges from <code>1</code> to {@link
697 * CharSequence#length() length}.
699 * <p> If the <code>char</code> value at <code>(index - 1)</code>
700 * is in the low-surrogate range, <code>(index - 2)</code> is not
701 * negative, and the <code>char</code> value at <code>(index -
702 * 2)</code> is in the high-surrogate range, then the
703 * supplementary code point value of the surrogate pair is
704 * returned. If the <code>char</code> value at <code>index -
705 * 1</code> is an unpaired low-surrogate or a high-surrogate, the
706 * surrogate value is returned.
708 * @param index the index following the code point that should be returned
709 * @return the Unicode code point value before the given index.
710 * @exception IndexOutOfBoundsException if the <code>index</code>
711 * argument is less than 1 or greater than the length
715 public int codePointBefore(int index) {
717 if ((i < 0) || (i >= length())) {
718 throw new StringIndexOutOfBoundsException(index);
720 return Character.codePointBeforeImpl(toCharArray(), offset() + index, offset());
724 * Returns the number of Unicode code points in the specified text
725 * range of this <code>String</code>. The text range begins at the
726 * specified <code>beginIndex</code> and extends to the
727 * <code>char</code> at index <code>endIndex - 1</code>. Thus the
728 * length (in <code>char</code>s) of the text range is
729 * <code>endIndex-beginIndex</code>. Unpaired surrogates within
730 * the text range count as one code point each.
732 * @param beginIndex the index to the first <code>char</code> of
734 * @param endIndex the index after the last <code>char</code> of
736 * @return the number of Unicode code points in the specified text
738 * @exception IndexOutOfBoundsException if the
739 * <code>beginIndex</code> is negative, or <code>endIndex</code>
740 * is larger than the length of this <code>String</code>, or
741 * <code>beginIndex</code> is larger than <code>endIndex</code>.
744 public int codePointCount(int beginIndex, int endIndex) {
745 if (beginIndex < 0 || endIndex > length() || beginIndex > endIndex) {
746 throw new IndexOutOfBoundsException();
748 return Character.codePointCountImpl(toCharArray(), offset()+beginIndex, endIndex-beginIndex);
752 * Returns the index within this <code>String</code> that is
753 * offset from the given <code>index</code> by
754 * <code>codePointOffset</code> code points. Unpaired surrogates
755 * within the text range given by <code>index</code> and
756 * <code>codePointOffset</code> count as one code point each.
758 * @param index the index to be offset
759 * @param codePointOffset the offset in code points
760 * @return the index within this <code>String</code>
761 * @exception IndexOutOfBoundsException if <code>index</code>
762 * is negative or larger then the length of this
763 * <code>String</code>, or if <code>codePointOffset</code> is positive
764 * and the substring starting with <code>index</code> has fewer
765 * than <code>codePointOffset</code> code points,
766 * or if <code>codePointOffset</code> is negative and the substring
767 * before <code>index</code> has fewer than the absolute value
768 * of <code>codePointOffset</code> code points.
771 public int offsetByCodePoints(int index, int codePointOffset) {
772 if (index < 0 || index > length()) {
773 throw new IndexOutOfBoundsException();
775 return Character.offsetByCodePointsImpl(toCharArray(), offset(), length(),
776 offset()+index, codePointOffset) - offset();
780 * Copy characters from this string into dst starting at dstBegin.
781 * This method doesn't perform any range checking.
783 @JavaScriptBody(args = { "arr", "to" }, body =
784 "var s = this.toString();\n" +
785 "for (var i = 0; i < s.length; i++) {\n" +
786 " arr[to++] = s[i];\n" +
789 void getChars(char dst[], int dstBegin) {
790 System.arraycopy(toCharArray(), offset(), dst, dstBegin, length());
794 * Copies characters from this string into the destination character
797 * The first character to be copied is at index <code>srcBegin</code>;
798 * the last character to be copied is at index <code>srcEnd-1</code>
799 * (thus the total number of characters to be copied is
800 * <code>srcEnd-srcBegin</code>). The characters are copied into the
801 * subarray of <code>dst</code> starting at index <code>dstBegin</code>
802 * and ending at index:
803 * <p><blockquote><pre>
804 * dstbegin + (srcEnd-srcBegin) - 1
805 * </pre></blockquote>
807 * @param srcBegin index of the first character in the string
809 * @param srcEnd index after the last character in the string
811 * @param dst the destination array.
812 * @param dstBegin the start offset in the destination array.
813 * @exception IndexOutOfBoundsException If any of the following
815 * <ul><li><code>srcBegin</code> is negative.
816 * <li><code>srcBegin</code> is greater than <code>srcEnd</code>
817 * <li><code>srcEnd</code> is greater than the length of this
819 * <li><code>dstBegin</code> is negative
820 * <li><code>dstBegin+(srcEnd-srcBegin)</code> is larger than
821 * <code>dst.length</code></ul>
823 @JavaScriptBody(args = { "beg", "end", "arr", "dst" }, body=
824 "var s = this.toString();\n" +
825 "while (beg < end) {\n" +
826 " arr[dst++] = s.charCodeAt(beg++);\n" +
829 public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
831 throw new StringIndexOutOfBoundsException(srcBegin);
833 if (srcEnd > length()) {
834 throw new StringIndexOutOfBoundsException(srcEnd);
836 if (srcBegin > srcEnd) {
837 throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
839 System.arraycopy(toCharArray(), offset() + srcBegin, dst, dstBegin,
844 * Copies characters from this string into the destination byte array. Each
845 * byte receives the 8 low-order bits of the corresponding character. The
846 * eight high-order bits of each character are not copied and do not
847 * participate in the transfer in any way.
849 * <p> The first character to be copied is at index {@code srcBegin}; the
850 * last character to be copied is at index {@code srcEnd-1}. The total
851 * number of characters to be copied is {@code srcEnd-srcBegin}. The
852 * characters, converted to bytes, are copied into the subarray of {@code
853 * dst} starting at index {@code dstBegin} and ending at index:
856 * dstbegin + (srcEnd-srcBegin) - 1
857 * </pre></blockquote>
859 * @deprecated This method does not properly convert characters into
860 * bytes. As of JDK 1.1, the preferred way to do this is via the
861 * {@link #getBytes()} method, which uses the platform's default charset.
864 * Index of the first character in the string to copy
867 * Index after the last character in the string to copy
870 * The destination array
873 * The start offset in the destination array
875 * @throws IndexOutOfBoundsException
876 * If any of the following is true:
878 * <li> {@code srcBegin} is negative
879 * <li> {@code srcBegin} is greater than {@code srcEnd}
880 * <li> {@code srcEnd} is greater than the length of this String
881 * <li> {@code dstBegin} is negative
882 * <li> {@code dstBegin+(srcEnd-srcBegin)} is larger than {@code
887 public void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin) {
889 throw new StringIndexOutOfBoundsException(srcBegin);
891 if (srcEnd > length()) {
892 throw new StringIndexOutOfBoundsException(srcEnd);
894 if (srcBegin > srcEnd) {
895 throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
898 int n = offset() + srcEnd;
899 int i = offset() + srcBegin;
900 char[] val = toCharArray(); /* avoid getfield opcode */
903 dst[j++] = (byte)val[i++];
908 * Encodes this {@code String} into a sequence of bytes using the named
909 * charset, storing the result into a new byte array.
911 * <p> The behavior of this method when this string cannot be encoded in
912 * the given charset is unspecified. The {@link
913 * java.nio.charset.CharsetEncoder} class should be used when more control
914 * over the encoding process is required.
917 * The name of a supported {@linkplain java.nio.charset.Charset
920 * @return The resultant byte array
922 * @throws UnsupportedEncodingException
923 * If the named charset is not supported
927 public byte[] getBytes(String charsetName)
928 throws UnsupportedEncodingException
930 checkUTF8(null, charsetName);
935 * Encodes this {@code String} into a sequence of bytes using the given
936 * {@linkplain java.nio.charset.Charset charset}, storing the result into a
939 * <p> This method always replaces malformed-input and unmappable-character
940 * sequences with this charset's default replacement byte array. The
941 * {@link java.nio.charset.CharsetEncoder} class should be used when more
942 * control over the encoding process is required.
945 * The {@linkplain java.nio.charset.Charset} to be used to encode
948 * @return The resultant byte array
952 /* don't want dep on Charset
953 public byte[] getBytes(Charset charset) {
954 if (charset == null) throw new NullPointerException();
955 return StringCoding.encode(charset, value, offset, count);
960 * Encodes this {@code String} into a sequence of bytes using the
961 * platform's default charset, storing the result into a new byte array.
963 * <p> The behavior of this method when this string cannot be encoded in
964 * the default charset is unspecified. The {@link
965 * java.nio.charset.CharsetEncoder} class should be used when more control
966 * over the encoding process is required.
968 * @return The resultant byte array
972 public byte[] getBytes() {
974 byte[] arr = new byte[len];
975 for (int i = 0, j = 0; j < len; j++) {
976 final int v = charAt(j);
982 arr = System.expandArray(arr, i + 1);
983 arr[i++] = (byte) (0xC0 | (v >> 6));
984 arr[i++] = (byte) (0x80 | (0x3F & v));
987 arr = System.expandArray(arr, i + 2);
988 arr[i++] = (byte) (0xE0 | (v >> 12));
989 arr[i++] = (byte) (0x80 | ((v >> 6) & 0x7F));
990 arr[i++] = (byte) (0x80 | (0x3F & v));
996 * Compares this string to the specified object. The result is {@code
997 * true} if and only if the argument is not {@code null} and is a {@code
998 * String} object that represents the same sequence of characters as this
1002 * The object to compare this {@code String} against
1004 * @return {@code true} if the given object represents a {@code String}
1005 * equivalent to this string, {@code false} otherwise
1007 * @see #compareTo(String)
1008 * @see #equalsIgnoreCase(String)
1010 @JavaScriptBody(args = { "obj" }, body =
1011 "return obj != null && obj.$instOf_java_lang_String && "
1012 + "this.toString() === obj.toString();"
1014 public boolean equals(Object anObject) {
1015 if (this == anObject) {
1018 if (anObject instanceof String) {
1019 String anotherString = (String)anObject;
1021 if (n == anotherString.length()) {
1022 char v1[] = toCharArray();
1023 char v2[] = anotherString.toCharArray();
1025 int j = anotherString.offset();
1027 if (v1[i++] != v2[j++])
1037 * Compares this string to the specified {@code StringBuffer}. The result
1038 * is {@code true} if and only if this {@code String} represents the same
1039 * sequence of characters as the specified {@code StringBuffer}.
1042 * The {@code StringBuffer} to compare this {@code String} against
1044 * @return {@code true} if this {@code String} represents the same
1045 * sequence of characters as the specified {@code StringBuffer},
1046 * {@code false} otherwise
1050 public boolean contentEquals(StringBuffer sb) {
1052 return contentEquals((CharSequence)sb);
1057 * Compares this string to the specified {@code CharSequence}. The result
1058 * is {@code true} if and only if this {@code String} represents the same
1059 * sequence of char values as the specified sequence.
1062 * The sequence to compare this {@code String} against
1064 * @return {@code true} if this {@code String} represents the same
1065 * sequence of char values as the specified sequence, {@code
1070 public boolean contentEquals(CharSequence cs) {
1071 if (length() != cs.length())
1073 // Argument is a StringBuffer, StringBuilder
1074 if (cs instanceof AbstractStringBuilder) {
1075 char v1[] = toCharArray();
1076 char v2[] = ((AbstractStringBuilder)cs).getValue();
1081 if (v1[i++] != v2[j++])
1086 // Argument is a String
1087 if (cs.equals(this))
1089 // Argument is a generic CharSequence
1090 char v1[] = toCharArray();
1095 if (v1[i++] != cs.charAt(j++))
1102 * Compares this {@code String} to another {@code String}, ignoring case
1103 * considerations. Two strings are considered equal ignoring case if they
1104 * are of the same length and corresponding characters in the two strings
1105 * are equal ignoring case.
1107 * <p> Two characters {@code c1} and {@code c2} are considered the same
1108 * ignoring case if at least one of the following is true:
1110 * <li> The two characters are the same (as compared by the
1111 * {@code ==} operator)
1112 * <li> Applying the method {@link
1113 * java.lang.Character#toUpperCase(char)} to each character
1114 * produces the same result
1115 * <li> Applying the method {@link
1116 * java.lang.Character#toLowerCase(char)} to each character
1117 * produces the same result
1120 * @param anotherString
1121 * The {@code String} to compare this {@code String} against
1123 * @return {@code true} if the argument is not {@code null} and it
1124 * represents an equivalent {@code String} ignoring case; {@code
1127 * @see #equals(Object)
1129 public boolean equalsIgnoreCase(String anotherString) {
1130 return (this == anotherString) ? true :
1131 (anotherString != null) && (anotherString.length() == length()) &&
1132 regionMatches(true, 0, anotherString, 0, length());
1136 * Compares two strings lexicographically.
1137 * The comparison is based on the Unicode value of each character in
1138 * the strings. The character sequence represented by this
1139 * <code>String</code> object is compared lexicographically to the
1140 * character sequence represented by the argument string. The result is
1141 * a negative integer if this <code>String</code> object
1142 * lexicographically precedes the argument string. The result is a
1143 * positive integer if this <code>String</code> object lexicographically
1144 * follows the argument string. The result is zero if the strings
1145 * are equal; <code>compareTo</code> returns <code>0</code> exactly when
1146 * the {@link #equals(Object)} method would return <code>true</code>.
1148 * This is the definition of lexicographic ordering. If two strings are
1149 * different, then either they have different characters at some index
1150 * that is a valid index for both strings, or their lengths are different,
1151 * or both. If they have different characters at one or more index
1152 * positions, let <i>k</i> be the smallest such index; then the string
1153 * whose character at position <i>k</i> has the smaller value, as
1154 * determined by using the < operator, lexicographically precedes the
1155 * other string. In this case, <code>compareTo</code> returns the
1156 * difference of the two character values at position <code>k</code> in
1157 * the two string -- that is, the value:
1159 * this.charAt(k)-anotherString.charAt(k)
1160 * </pre></blockquote>
1161 * If there is no index position at which they differ, then the shorter
1162 * string lexicographically precedes the longer string. In this case,
1163 * <code>compareTo</code> returns the difference of the lengths of the
1164 * strings -- that is, the value:
1166 * this.length()-anotherString.length()
1167 * </pre></blockquote>
1169 * @param anotherString the <code>String</code> to be compared.
1170 * @return the value <code>0</code> if the argument string is equal to
1171 * this string; a value less than <code>0</code> if this string
1172 * is lexicographically less than the string argument; and a
1173 * value greater than <code>0</code> if this string is
1174 * lexicographically greater than the string argument.
1176 public int compareTo(String anotherString) {
1177 int len1 = length();
1178 int len2 = anotherString.length();
1179 int n = Math.min(len1, len2);
1180 char v1[] = toCharArray();
1181 char v2[] = anotherString.toCharArray();
1183 int j = anotherString.offset();
1209 * A Comparator that orders <code>String</code> objects as by
1210 * <code>compareToIgnoreCase</code>. This comparator is serializable.
1212 * Note that this Comparator does <em>not</em> take locale into account,
1213 * and will result in an unsatisfactory ordering for certain locales.
1214 * The java.text package provides <em>Collators</em> to allow
1215 * locale-sensitive ordering.
1217 * @see java.text.Collator#compare(String, String)
1220 public static final Comparator<String> CASE_INSENSITIVE_ORDER
1221 = new CaseInsensitiveComparator();
1223 private static int offset() {
1227 private static class CaseInsensitiveComparator
1228 implements Comparator<String>, java.io.Serializable {
1229 // use serialVersionUID from JDK 1.2.2 for interoperability
1230 private static final long serialVersionUID = 8575799808933029326L;
1232 public int compare(String s1, String s2) {
1233 int n1 = s1.length();
1234 int n2 = s2.length();
1235 int min = Math.min(n1, n2);
1236 for (int i = 0; i < min; i++) {
1237 char c1 = s1.charAt(i);
1238 char c2 = s2.charAt(i);
1240 c1 = Character.toUpperCase(c1);
1241 c2 = Character.toUpperCase(c2);
1243 c1 = Character.toLowerCase(c1);
1244 c2 = Character.toLowerCase(c2);
1246 // No overflow because of numeric promotion
1257 * Compares two strings lexicographically, ignoring case
1258 * differences. This method returns an integer whose sign is that of
1259 * calling <code>compareTo</code> with normalized versions of the strings
1260 * where case differences have been eliminated by calling
1261 * <code>Character.toLowerCase(Character.toUpperCase(character))</code> on
1264 * Note that this method does <em>not</em> take locale into account,
1265 * and will result in an unsatisfactory ordering for certain locales.
1266 * The java.text package provides <em>collators</em> to allow
1267 * locale-sensitive ordering.
1269 * @param str the <code>String</code> to be compared.
1270 * @return a negative integer, zero, or a positive integer as the
1271 * specified String is greater than, equal to, or less
1272 * than this String, ignoring case considerations.
1273 * @see java.text.Collator#compare(String, String)
1276 public int compareToIgnoreCase(String str) {
1277 return CASE_INSENSITIVE_ORDER.compare(this, str);
1281 * Tests if two string regions are equal.
1283 * A substring of this <tt>String</tt> object is compared to a substring
1284 * of the argument other. The result is true if these substrings
1285 * represent identical character sequences. The substring of this
1286 * <tt>String</tt> object to be compared begins at index <tt>toffset</tt>
1287 * and has length <tt>len</tt>. The substring of other to be compared
1288 * begins at index <tt>ooffset</tt> and has length <tt>len</tt>. The
1289 * result is <tt>false</tt> if and only if at least one of the following
1291 * <ul><li><tt>toffset</tt> is negative.
1292 * <li><tt>ooffset</tt> is negative.
1293 * <li><tt>toffset+len</tt> is greater than the length of this
1294 * <tt>String</tt> object.
1295 * <li><tt>ooffset+len</tt> is greater than the length of the other
1297 * <li>There is some nonnegative integer <i>k</i> less than <tt>len</tt>
1299 * <tt>this.charAt(toffset+<i>k</i>) != other.charAt(ooffset+<i>k</i>)</tt>
1302 * @param toffset the starting offset of the subregion in this string.
1303 * @param other the string argument.
1304 * @param ooffset the starting offset of the subregion in the string
1306 * @param len the number of characters to compare.
1307 * @return <code>true</code> if the specified subregion of this string
1308 * exactly matches the specified subregion of the string argument;
1309 * <code>false</code> otherwise.
1311 public boolean regionMatches(int toffset, String other, int ooffset,
1313 char ta[] = toCharArray();
1314 int to = offset() + toffset;
1315 char pa[] = other.toCharArray();
1316 int po = other.offset() + ooffset;
1317 // Note: toffset, ooffset, or len might be near -1>>>1.
1318 if ((ooffset < 0) || (toffset < 0) || (toffset > (long)length() - len)
1319 || (ooffset > (long)other.length() - len)) {
1323 if (ta[to++] != pa[po++]) {
1331 * Tests if two string regions are equal.
1333 * A substring of this <tt>String</tt> object is compared to a substring
1334 * of the argument <tt>other</tt>. The result is <tt>true</tt> if these
1335 * substrings represent character sequences that are the same, ignoring
1336 * case if and only if <tt>ignoreCase</tt> is true. The substring of
1337 * this <tt>String</tt> object to be compared begins at index
1338 * <tt>toffset</tt> and has length <tt>len</tt>. The substring of
1339 * <tt>other</tt> to be compared begins at index <tt>ooffset</tt> and
1340 * has length <tt>len</tt>. The result is <tt>false</tt> if and only if
1341 * at least one of the following is true:
1342 * <ul><li><tt>toffset</tt> is negative.
1343 * <li><tt>ooffset</tt> is negative.
1344 * <li><tt>toffset+len</tt> is greater than the length of this
1345 * <tt>String</tt> object.
1346 * <li><tt>ooffset+len</tt> is greater than the length of the other
1348 * <li><tt>ignoreCase</tt> is <tt>false</tt> and there is some nonnegative
1349 * integer <i>k</i> less than <tt>len</tt> such that:
1351 * this.charAt(toffset+k) != other.charAt(ooffset+k)
1352 * </pre></blockquote>
1353 * <li><tt>ignoreCase</tt> is <tt>true</tt> and there is some nonnegative
1354 * integer <i>k</i> less than <tt>len</tt> such that:
1356 * Character.toLowerCase(this.charAt(toffset+k)) !=
1357 Character.toLowerCase(other.charAt(ooffset+k))
1358 * </pre></blockquote>
1361 * Character.toUpperCase(this.charAt(toffset+k)) !=
1362 * Character.toUpperCase(other.charAt(ooffset+k))
1363 * </pre></blockquote>
1366 * @param ignoreCase if <code>true</code>, ignore case when comparing
1368 * @param toffset the starting offset of the subregion in this
1370 * @param other the string argument.
1371 * @param ooffset the starting offset of the subregion in the string
1373 * @param len the number of characters to compare.
1374 * @return <code>true</code> if the specified subregion of this string
1375 * matches the specified subregion of the string argument;
1376 * <code>false</code> otherwise. Whether the matching is exact
1377 * or case insensitive depends on the <code>ignoreCase</code>
1380 public boolean regionMatches(boolean ignoreCase, int toffset,
1381 String other, int ooffset, int len) {
1382 char ta[] = toCharArray();
1383 int to = offset() + toffset;
1384 char pa[] = other.toCharArray();
1385 int po = other.offset() + ooffset;
1386 // Note: toffset, ooffset, or len might be near -1>>>1.
1387 if ((ooffset < 0) || (toffset < 0) || (toffset > (long)length() - len) ||
1388 (ooffset > (long)other.length() - len)) {
1398 // If characters don't match but case may be ignored,
1399 // try converting both characters to uppercase.
1400 // If the results match, then the comparison scan should
1402 char u1 = Character.toUpperCase(c1);
1403 char u2 = Character.toUpperCase(c2);
1407 // Unfortunately, conversion to uppercase does not work properly
1408 // for the Georgian alphabet, which has strange rules about case
1409 // conversion. So we need to make one last check before
1411 if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) {
1421 * Tests if the substring of this string beginning at the
1422 * specified index starts with the specified prefix.
1424 * @param prefix the prefix.
1425 * @param toffset where to begin looking in this string.
1426 * @return <code>true</code> if the character sequence represented by the
1427 * argument is a prefix of the substring of this object starting
1428 * at index <code>toffset</code>; <code>false</code> otherwise.
1429 * The result is <code>false</code> if <code>toffset</code> is
1430 * negative or greater than the length of this
1431 * <code>String</code> object; otherwise the result is the same
1432 * as the result of the expression
1434 * this.substring(toffset).startsWith(prefix)
1437 @JavaScriptBody(args = { "find", "from" }, body=
1438 "find = find.toString();\n" +
1439 "return this.toString().substring(from, from + find.length) === find;\n"
1441 public boolean startsWith(String prefix, int toffset) {
1442 char ta[] = toCharArray();
1443 int to = offset() + toffset;
1444 char pa[] = prefix.toCharArray();
1445 int po = prefix.offset();
1446 int pc = prefix.length();
1447 // Note: toffset might be near -1>>>1.
1448 if ((toffset < 0) || (toffset > length() - pc)) {
1452 if (ta[to++] != pa[po++]) {
1460 * Tests if this string starts with the specified prefix.
1462 * @param prefix the prefix.
1463 * @return <code>true</code> if the character sequence represented by the
1464 * argument is a prefix of the character sequence represented by
1465 * this string; <code>false</code> otherwise.
1466 * Note also that <code>true</code> will be returned if the
1467 * argument is an empty string or is equal to this
1468 * <code>String</code> object as determined by the
1469 * {@link #equals(Object)} method.
1472 public boolean startsWith(String prefix) {
1473 return startsWith(prefix, 0);
1477 * Tests if this string ends with the specified suffix.
1479 * @param suffix the suffix.
1480 * @return <code>true</code> if the character sequence represented by the
1481 * argument is a suffix of the character sequence represented by
1482 * this object; <code>false</code> otherwise. Note that the
1483 * result will be <code>true</code> if the argument is the
1484 * empty string or is equal to this <code>String</code> object
1485 * as determined by the {@link #equals(Object)} method.
1487 public boolean endsWith(String suffix) {
1488 return startsWith(suffix, length() - suffix.length());
1492 * Returns a hash code for this string. The hash code for a
1493 * <code>String</code> object is computed as
1495 * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
1496 * </pre></blockquote>
1497 * using <code>int</code> arithmetic, where <code>s[i]</code> is the
1498 * <i>i</i>th character of the string, <code>n</code> is the length of
1499 * the string, and <code>^</code> indicates exponentiation.
1500 * (The hash value of the empty string is zero.)
1502 * @return a hash code value for this object.
1504 public int hashCode() {
1505 return super.hashCode();
1507 int computeHashCode() {
1509 if (h == 0 && length() > 0) {
1513 for (int i = 0; i < len; i++) {
1514 h = 31*h + charAt(off++);
1521 * Returns the index within this string of the first occurrence of
1522 * the specified character. If a character with value
1523 * <code>ch</code> occurs in the character sequence represented by
1524 * this <code>String</code> object, then the index (in Unicode
1525 * code units) of the first such occurrence is returned. For
1526 * values of <code>ch</code> in the range from 0 to 0xFFFF
1527 * (inclusive), this is the smallest value <i>k</i> such that:
1529 * this.charAt(<i>k</i>) == ch
1530 * </pre></blockquote>
1531 * is true. For other values of <code>ch</code>, it is the
1532 * smallest value <i>k</i> such that:
1534 * this.codePointAt(<i>k</i>) == ch
1535 * </pre></blockquote>
1536 * is true. In either case, if no such character occurs in this
1537 * string, then <code>-1</code> is returned.
1539 * @param ch a character (Unicode code point).
1540 * @return the index of the first occurrence of the character in the
1541 * character sequence represented by this object, or
1542 * <code>-1</code> if the character does not occur.
1544 public int indexOf(int ch) {
1545 return indexOf(ch, 0);
1549 * Returns the index within this string of the first occurrence of the
1550 * specified character, starting the search at the specified index.
1552 * If a character with value <code>ch</code> occurs in the
1553 * character sequence represented by this <code>String</code>
1554 * object at an index no smaller than <code>fromIndex</code>, then
1555 * the index of the first such occurrence is returned. For values
1556 * of <code>ch</code> in the range from 0 to 0xFFFF (inclusive),
1557 * this is the smallest value <i>k</i> such that:
1559 * (this.charAt(<i>k</i>) == ch) && (<i>k</i> >= fromIndex)
1560 * </pre></blockquote>
1561 * is true. For other values of <code>ch</code>, it is the
1562 * smallest value <i>k</i> such that:
1564 * (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> >= fromIndex)
1565 * </pre></blockquote>
1566 * is true. In either case, if no such character occurs in this
1567 * string at or after position <code>fromIndex</code>, then
1568 * <code>-1</code> is returned.
1571 * There is no restriction on the value of <code>fromIndex</code>. If it
1572 * is negative, it has the same effect as if it were zero: this entire
1573 * string may be searched. If it is greater than the length of this
1574 * string, it has the same effect as if it were equal to the length of
1575 * this string: <code>-1</code> is returned.
1577 * <p>All indices are specified in <code>char</code> values
1578 * (Unicode code units).
1580 * @param ch a character (Unicode code point).
1581 * @param fromIndex the index to start the search from.
1582 * @return the index of the first occurrence of the character in the
1583 * character sequence represented by this object that is greater
1584 * than or equal to <code>fromIndex</code>, or <code>-1</code>
1585 * if the character does not occur.
1587 @JavaScriptBody(args = { "ch", "from" }, body =
1588 "if (typeof ch === 'number') ch = String.fromCharCode(ch);\n" +
1589 "return this.toString().indexOf(ch, from);\n"
1591 public int indexOf(int ch, int fromIndex) {
1592 if (fromIndex < 0) {
1594 } else if (fromIndex >= length()) {
1595 // Note: fromIndex might be near -1>>>1.
1599 if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
1600 // handle most cases here (ch is a BMP code point or a
1601 // negative value (invalid code point))
1602 final char[] value = this.toCharArray();
1603 final int offset = this.offset();
1604 final int max = offset + length();
1605 for (int i = offset + fromIndex; i < max ; i++) {
1606 if (value[i] == ch) {
1612 return indexOfSupplementary(ch, fromIndex);
1617 * Handles (rare) calls of indexOf with a supplementary character.
1619 private int indexOfSupplementary(int ch, int fromIndex) {
1620 if (Character.isValidCodePoint(ch)) {
1621 final char[] value = this.toCharArray();
1622 final int offset = this.offset();
1623 final char hi = Character.highSurrogate(ch);
1624 final char lo = Character.lowSurrogate(ch);
1625 final int max = offset + length() - 1;
1626 for (int i = offset + fromIndex; i < max; i++) {
1627 if (value[i] == hi && value[i+1] == lo) {
1636 * Returns the index within this string of the last occurrence of
1637 * the specified character. For values of <code>ch</code> in the
1638 * range from 0 to 0xFFFF (inclusive), the index (in Unicode code
1639 * units) returned is the largest value <i>k</i> such that:
1641 * this.charAt(<i>k</i>) == ch
1642 * </pre></blockquote>
1643 * is true. For other values of <code>ch</code>, it is the
1644 * largest value <i>k</i> such that:
1646 * this.codePointAt(<i>k</i>) == ch
1647 * </pre></blockquote>
1648 * is true. In either case, if no such character occurs in this
1649 * string, then <code>-1</code> is returned. The
1650 * <code>String</code> is searched backwards starting at the last
1653 * @param ch a character (Unicode code point).
1654 * @return the index of the last occurrence of the character in the
1655 * character sequence represented by this object, or
1656 * <code>-1</code> if the character does not occur.
1658 public int lastIndexOf(int ch) {
1659 return lastIndexOf(ch, length() - 1);
1663 * Returns the index within this string of the last occurrence of
1664 * the specified character, searching backward starting at the
1665 * specified index. For values of <code>ch</code> in the range
1666 * from 0 to 0xFFFF (inclusive), the index returned is the largest
1667 * value <i>k</i> such that:
1669 * (this.charAt(<i>k</i>) == ch) && (<i>k</i> <= fromIndex)
1670 * </pre></blockquote>
1671 * is true. For other values of <code>ch</code>, it is the
1672 * largest value <i>k</i> such that:
1674 * (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> <= fromIndex)
1675 * </pre></blockquote>
1676 * is true. In either case, if no such character occurs in this
1677 * string at or before position <code>fromIndex</code>, then
1678 * <code>-1</code> is returned.
1680 * <p>All indices are specified in <code>char</code> values
1681 * (Unicode code units).
1683 * @param ch a character (Unicode code point).
1684 * @param fromIndex the index to start the search from. There is no
1685 * restriction on the value of <code>fromIndex</code>. If it is
1686 * greater than or equal to the length of this string, it has
1687 * the same effect as if it were equal to one less than the
1688 * length of this string: this entire string may be searched.
1689 * If it is negative, it has the same effect as if it were -1:
1691 * @return the index of the last occurrence of the character in the
1692 * character sequence represented by this object that is less
1693 * than or equal to <code>fromIndex</code>, or <code>-1</code>
1694 * if the character does not occur before that point.
1696 @JavaScriptBody(args = { "ch", "from" }, body =
1697 "if (typeof ch === 'number') ch = String.fromCharCode(ch);\n" +
1698 "return this.toString().lastIndexOf(ch, from);"
1700 public int lastIndexOf(int ch, int fromIndex) {
1701 if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
1702 // handle most cases here (ch is a BMP code point or a
1703 // negative value (invalid code point))
1704 final char[] value = this.toCharArray();
1705 final int offset = this.offset();
1706 int i = offset + Math.min(fromIndex, length() - 1);
1707 for (; i >= offset ; i--) {
1708 if (value[i] == ch) {
1714 return lastIndexOfSupplementary(ch, fromIndex);
1719 * Handles (rare) calls of lastIndexOf with a supplementary character.
1721 private int lastIndexOfSupplementary(int ch, int fromIndex) {
1722 if (Character.isValidCodePoint(ch)) {
1723 final char[] value = this.toCharArray();
1724 final int offset = this.offset();
1725 char hi = Character.highSurrogate(ch);
1726 char lo = Character.lowSurrogate(ch);
1727 int i = offset + Math.min(fromIndex, length() - 2);
1728 for (; i >= offset; i--) {
1729 if (value[i] == hi && value[i+1] == lo) {
1738 * Returns the index within this string of the first occurrence of the
1739 * specified substring.
1741 * <p>The returned index is the smallest value <i>k</i> for which:
1743 * this.startsWith(str, <i>k</i>)
1744 * </pre></blockquote>
1745 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1747 * @param str the substring to search for.
1748 * @return the index of the first occurrence of the specified substring,
1749 * or {@code -1} if there is no such occurrence.
1751 public int indexOf(String str) {
1752 return indexOf(str, 0);
1756 * Returns the index within this string of the first occurrence of the
1757 * specified substring, starting at the specified index.
1759 * <p>The returned index is the smallest value <i>k</i> for which:
1761 * <i>k</i> >= fromIndex && this.startsWith(str, <i>k</i>)
1762 * </pre></blockquote>
1763 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1765 * @param str the substring to search for.
1766 * @param fromIndex the index from which to start the search.
1767 * @return the index of the first occurrence of the specified substring,
1768 * starting at the specified index,
1769 * or {@code -1} if there is no such occurrence.
1771 @JavaScriptBody(args = { "str", "fromIndex" }, body =
1772 "return this.toString().indexOf(str.toString(), fromIndex);"
1774 public native int indexOf(String str, int fromIndex);
1777 * Returns the index within this string of the last occurrence of the
1778 * specified substring. The last occurrence of the empty string ""
1779 * is considered to occur at the index value {@code this.length()}.
1781 * <p>The returned index is the largest value <i>k</i> for which:
1783 * this.startsWith(str, <i>k</i>)
1784 * </pre></blockquote>
1785 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1787 * @param str the substring to search for.
1788 * @return the index of the last occurrence of the specified substring,
1789 * or {@code -1} if there is no such occurrence.
1791 public int lastIndexOf(String str) {
1792 return lastIndexOf(str, length());
1796 * Returns the index within this string of the last occurrence of the
1797 * specified substring, searching backward starting at the specified index.
1799 * <p>The returned index is the largest value <i>k</i> for which:
1801 * <i>k</i> <= fromIndex && this.startsWith(str, <i>k</i>)
1802 * </pre></blockquote>
1803 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1805 * @param str the substring to search for.
1806 * @param fromIndex the index to start the search from.
1807 * @return the index of the last occurrence of the specified substring,
1808 * searching backward from the specified index,
1809 * or {@code -1} if there is no such occurrence.
1811 @JavaScriptBody(args = { "s", "from" }, body =
1812 "return this.toString().lastIndexOf(s.toString(), from);"
1814 public int lastIndexOf(String str, int fromIndex) {
1815 return lastIndexOf(toCharArray(), offset(), length(), str.toCharArray(), str.offset(), str.length(), fromIndex);
1819 * Code shared by String and StringBuffer to do searches. The
1820 * source is the character array being searched, and the target
1821 * is the string being searched for.
1823 * @param source the characters being searched.
1824 * @param sourceOffset offset of the source string.
1825 * @param sourceCount count of the source string.
1826 * @param target the characters being searched for.
1827 * @param targetOffset offset of the target string.
1828 * @param targetCount count of the target string.
1829 * @param fromIndex the index to begin searching from.
1831 static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
1832 char[] target, int targetOffset, int targetCount,
1835 * Check arguments; return immediately where possible. For
1836 * consistency, don't check for null str.
1838 int rightIndex = sourceCount - targetCount;
1839 if (fromIndex < 0) {
1842 if (fromIndex > rightIndex) {
1843 fromIndex = rightIndex;
1845 /* Empty string always matches. */
1846 if (targetCount == 0) {
1850 int strLastIndex = targetOffset + targetCount - 1;
1851 char strLastChar = target[strLastIndex];
1852 int min = sourceOffset + targetCount - 1;
1853 int i = min + fromIndex;
1855 startSearchForLastChar:
1857 while (i >= min && source[i] != strLastChar) {
1864 int start = j - (targetCount - 1);
1865 int k = strLastIndex - 1;
1868 if (source[j--] != target[k--]) {
1870 continue startSearchForLastChar;
1873 return start - sourceOffset + 1;
1878 * Returns a new string that is a substring of this string. The
1879 * substring begins with the character at the specified index and
1880 * extends to the end of this string. <p>
1883 * "unhappy".substring(2) returns "happy"
1884 * "Harbison".substring(3) returns "bison"
1885 * "emptiness".substring(9) returns "" (an empty string)
1886 * </pre></blockquote>
1888 * @param beginIndex the beginning index, inclusive.
1889 * @return the specified substring.
1890 * @exception IndexOutOfBoundsException if
1891 * <code>beginIndex</code> is negative or larger than the
1892 * length of this <code>String</code> object.
1894 public String substring(int beginIndex) {
1895 return substring(beginIndex, length());
1899 * Returns a new string that is a substring of this string. The
1900 * substring begins at the specified <code>beginIndex</code> and
1901 * extends to the character at index <code>endIndex - 1</code>.
1902 * Thus the length of the substring is <code>endIndex-beginIndex</code>.
1906 * "hamburger".substring(4, 8) returns "urge"
1907 * "smiles".substring(1, 5) returns "mile"
1908 * </pre></blockquote>
1910 * @param beginIndex the beginning index, inclusive.
1911 * @param endIndex the ending index, exclusive.
1912 * @return the specified substring.
1913 * @exception IndexOutOfBoundsException if the
1914 * <code>beginIndex</code> is negative, or
1915 * <code>endIndex</code> is larger than the length of
1916 * this <code>String</code> object, or
1917 * <code>beginIndex</code> is larger than
1918 * <code>endIndex</code>.
1920 @JavaScriptBody(args = { "beginIndex", "endIndex" }, body =
1921 "return this.toString().substring(beginIndex, endIndex);"
1923 public String substring(int beginIndex, int endIndex) {
1924 if (beginIndex < 0) {
1925 throw new StringIndexOutOfBoundsException(beginIndex);
1927 if (endIndex > length()) {
1928 throw new StringIndexOutOfBoundsException(endIndex);
1930 if (beginIndex > endIndex) {
1931 throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
1933 return ((beginIndex == 0) && (endIndex == length())) ? this :
1934 new String(toCharArray(), offset() + beginIndex, endIndex - beginIndex);
1938 * Returns a new character sequence that is a subsequence of this sequence.
1940 * <p> An invocation of this method of the form
1943 * str.subSequence(begin, end)</pre></blockquote>
1945 * behaves in exactly the same way as the invocation
1948 * str.substring(begin, end)</pre></blockquote>
1950 * This method is defined so that the <tt>String</tt> class can implement
1951 * the {@link CharSequence} interface. </p>
1953 * @param beginIndex the begin index, inclusive.
1954 * @param endIndex the end index, exclusive.
1955 * @return the specified subsequence.
1957 * @throws IndexOutOfBoundsException
1958 * if <tt>beginIndex</tt> or <tt>endIndex</tt> are negative,
1959 * if <tt>endIndex</tt> is greater than <tt>length()</tt>,
1960 * or if <tt>beginIndex</tt> is greater than <tt>startIndex</tt>
1965 public CharSequence subSequence(int beginIndex, int endIndex) {
1966 return this.substring(beginIndex, endIndex);
1970 * Concatenates the specified string to the end of this string.
1972 * If the length of the argument string is <code>0</code>, then this
1973 * <code>String</code> object is returned. Otherwise, a new
1974 * <code>String</code> object is created, representing a character
1975 * sequence that is the concatenation of the character sequence
1976 * represented by this <code>String</code> object and the character
1977 * sequence represented by the argument string.<p>
1980 * "cares".concat("s") returns "caress"
1981 * "to".concat("get").concat("her") returns "together"
1982 * </pre></blockquote>
1984 * @param str the <code>String</code> that is concatenated to the end
1985 * of this <code>String</code>.
1986 * @return a string that represents the concatenation of this object's
1987 * characters followed by the string argument's characters.
1989 public String concat(String str) {
1990 int otherLen = str.length();
1991 if (otherLen == 0) {
1994 char buf[] = new char[length() + otherLen];
1995 getChars(0, length(), buf, 0);
1996 str.getChars(0, otherLen, buf, length());
1997 return new String(buf, 0, length() + otherLen);
2001 * Returns a new string resulting from replacing all occurrences of
2002 * <code>oldChar</code> in this string with <code>newChar</code>.
2004 * If the character <code>oldChar</code> does not occur in the
2005 * character sequence represented by this <code>String</code> object,
2006 * then a reference to this <code>String</code> object is returned.
2007 * Otherwise, a new <code>String</code> object is created that
2008 * represents a character sequence identical to the character sequence
2009 * represented by this <code>String</code> object, except that every
2010 * occurrence of <code>oldChar</code> is replaced by an occurrence
2011 * of <code>newChar</code>.
2015 * "mesquite in your cellar".replace('e', 'o')
2016 * returns "mosquito in your collar"
2017 * "the war of baronets".replace('r', 'y')
2018 * returns "the way of bayonets"
2019 * "sparring with a purple porpoise".replace('p', 't')
2020 * returns "starring with a turtle tortoise"
2021 * "JonL".replace('q', 'x') returns "JonL" (no change)
2022 * </pre></blockquote>
2024 * @param oldChar the old character.
2025 * @param newChar the new character.
2026 * @return a string derived from this string by replacing every
2027 * occurrence of <code>oldChar</code> with <code>newChar</code>.
2029 @JavaScriptBody(args = { "arg1", "arg2" }, body =
2030 "if (typeof arg1 === 'number') arg1 = String.fromCharCode(arg1);\n" +
2031 "if (typeof arg2 === 'number') arg2 = String.fromCharCode(arg2);\n" +
2032 "var s = this.toString();\n" +
2034 " var ret = s.replace(arg1, arg2);\n" +
2035 " if (ret === s) {\n" +
2041 public String replace(char oldChar, char newChar) {
2042 if (oldChar != newChar) {
2045 char[] val = toCharArray(); /* avoid getfield opcode */
2046 int off = offset(); /* avoid getfield opcode */
2049 if (val[off + i] == oldChar) {
2054 char buf[] = new char[len];
2055 for (int j = 0 ; j < i ; j++) {
2056 buf[j] = val[off+j];
2059 char c = val[off + i];
2060 buf[i] = (c == oldChar) ? newChar : c;
2063 return new String(buf, 0, len);
2070 * Tells whether or not this string matches the given <a
2071 * href="../util/regex/Pattern.html#sum">regular expression</a>.
2073 * <p> An invocation of this method of the form
2074 * <i>str</i><tt>.matches(</tt><i>regex</i><tt>)</tt> yields exactly the
2075 * same result as the expression
2077 * <blockquote><tt> {@link java.util.regex.Pattern}.{@link
2078 * java.util.regex.Pattern#matches(String,CharSequence)
2079 * matches}(</tt><i>regex</i><tt>,</tt> <i>str</i><tt>)</tt></blockquote>
2082 * the regular expression to which this string is to be matched
2084 * @return <tt>true</tt> if, and only if, this string matches the
2085 * given regular expression
2087 * @throws PatternSyntaxException
2088 * if the regular expression's syntax is invalid
2090 * @see java.util.regex.Pattern
2095 @JavaScriptBody(args = { "regex" }, body =
2096 "var self = this.toString();\n"
2097 + "var re = new RegExp(regex.toString());\n"
2098 + "var r = re.exec(self);\n"
2099 + "return r != null && r.length > 0 && self.length == r[0].length;"
2101 public boolean matches(String regex) {
2102 throw new UnsupportedOperationException();
2106 * Returns true if and only if this string contains the specified
2107 * sequence of char values.
2109 * @param s the sequence to search for
2110 * @return true if this string contains <code>s</code>, false otherwise
2111 * @throws NullPointerException if <code>s</code> is <code>null</code>
2114 public boolean contains(CharSequence s) {
2115 return indexOf(s.toString()) > -1;
2119 * Replaces the first substring of this string that matches the given <a
2120 * href="../util/regex/Pattern.html#sum">regular expression</a> with the
2121 * given replacement.
2123 * <p> An invocation of this method of the form
2124 * <i>str</i><tt>.replaceFirst(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt>
2125 * yields exactly the same result as the expression
2128 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2129 * compile}(</tt><i>regex</i><tt>).{@link
2130 * java.util.regex.Pattern#matcher(java.lang.CharSequence)
2131 * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceFirst
2132 * replaceFirst}(</tt><i>repl</i><tt>)</tt></blockquote>
2135 * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the
2136 * replacement string may cause the results to be different than if it were
2137 * being treated as a literal replacement string; see
2138 * {@link java.util.regex.Matcher#replaceFirst}.
2139 * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
2140 * meaning of these characters, if desired.
2143 * the regular expression to which this string is to be matched
2144 * @param replacement
2145 * the string to be substituted for the first match
2147 * @return The resulting <tt>String</tt>
2149 * @throws PatternSyntaxException
2150 * if the regular expression's syntax is invalid
2152 * @see java.util.regex.Pattern
2157 public String replaceFirst(String regex, String replacement) {
2158 throw new UnsupportedOperationException();
2162 * Replaces each substring of this string that matches the given <a
2163 * href="../util/regex/Pattern.html#sum">regular expression</a> with the
2164 * given replacement.
2166 * <p> An invocation of this method of the form
2167 * <i>str</i><tt>.replaceAll(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt>
2168 * yields exactly the same result as the expression
2171 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2172 * compile}(</tt><i>regex</i><tt>).{@link
2173 * java.util.regex.Pattern#matcher(java.lang.CharSequence)
2174 * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceAll
2175 * replaceAll}(</tt><i>repl</i><tt>)</tt></blockquote>
2178 * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the
2179 * replacement string may cause the results to be different than if it were
2180 * being treated as a literal replacement string; see
2181 * {@link java.util.regex.Matcher#replaceAll Matcher.replaceAll}.
2182 * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
2183 * meaning of these characters, if desired.
2186 * the regular expression to which this string is to be matched
2187 * @param replacement
2188 * the string to be substituted for each match
2190 * @return The resulting <tt>String</tt>
2192 * @throws PatternSyntaxException
2193 * if the regular expression's syntax is invalid
2195 * @see java.util.regex.Pattern
2200 public String replaceAll(String regex, String replacement) {
2201 throw new UnsupportedOperationException();
2205 * Replaces each substring of this string that matches the literal target
2206 * sequence with the specified literal replacement sequence. The
2207 * replacement proceeds from the beginning of the string to the end, for
2208 * example, replacing "aa" with "b" in the string "aaa" will result in
2209 * "ba" rather than "ab".
2211 * @param target The sequence of char values to be replaced
2212 * @param replacement The replacement sequence of char values
2213 * @return The resulting string
2214 * @throws NullPointerException if <code>target</code> or
2215 * <code>replacement</code> is <code>null</code>.
2218 public String replace(CharSequence target, CharSequence replacement) {
2219 throw new UnsupportedOperationException("This one should be supported, but without dep on rest of regexp");
2223 * Splits this string around matches of the given
2224 * <a href="../util/regex/Pattern.html#sum">regular expression</a>.
2226 * <p> The array returned by this method contains each substring of this
2227 * string that is terminated by another substring that matches the given
2228 * expression or is terminated by the end of the string. The substrings in
2229 * the array are in the order in which they occur in this string. If the
2230 * expression does not match any part of the input then the resulting array
2231 * has just one element, namely this string.
2233 * <p> The <tt>limit</tt> parameter controls the number of times the
2234 * pattern is applied and therefore affects the length of the resulting
2235 * array. If the limit <i>n</i> is greater than zero then the pattern
2236 * will be applied at most <i>n</i> - 1 times, the array's
2237 * length will be no greater than <i>n</i>, and the array's last entry
2238 * will contain all input beyond the last matched delimiter. If <i>n</i>
2239 * is non-positive then the pattern will be applied as many times as
2240 * possible and the array can have any length. If <i>n</i> is zero then
2241 * the pattern will be applied as many times as possible, the array can
2242 * have any length, and trailing empty strings will be discarded.
2244 * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the
2245 * following results with these parameters:
2247 * <blockquote><table cellpadding=1 cellspacing=0 summary="Split example showing regex, limit, and result">
2253 * <tr><td align=center>:</td>
2254 * <td align=center>2</td>
2255 * <td><tt>{ "boo", "and:foo" }</tt></td></tr>
2256 * <tr><td align=center>:</td>
2257 * <td align=center>5</td>
2258 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2259 * <tr><td align=center>:</td>
2260 * <td align=center>-2</td>
2261 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2262 * <tr><td align=center>o</td>
2263 * <td align=center>5</td>
2264 * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
2265 * <tr><td align=center>o</td>
2266 * <td align=center>-2</td>
2267 * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
2268 * <tr><td align=center>o</td>
2269 * <td align=center>0</td>
2270 * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
2271 * </table></blockquote>
2273 * <p> An invocation of this method of the form
2274 * <i>str.</i><tt>split(</tt><i>regex</i><tt>,</tt> <i>n</i><tt>)</tt>
2275 * yields the same result as the expression
2278 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2279 * compile}<tt>(</tt><i>regex</i><tt>)</tt>.{@link
2280 * java.util.regex.Pattern#split(java.lang.CharSequence,int)
2281 * split}<tt>(</tt><i>str</i><tt>,</tt> <i>n</i><tt>)</tt>
2286 * the delimiting regular expression
2289 * the result threshold, as described above
2291 * @return the array of strings computed by splitting this string
2292 * around matches of the given regular expression
2294 * @throws PatternSyntaxException
2295 * if the regular expression's syntax is invalid
2297 * @see java.util.regex.Pattern
2302 public String[] split(String regex, int limit) {
2303 throw new UnsupportedOperationException("Needs regexp");
2307 * Splits this string around matches of the given <a
2308 * href="../util/regex/Pattern.html#sum">regular expression</a>.
2310 * <p> This method works as if by invoking the two-argument {@link
2311 * #split(String, int) split} method with the given expression and a limit
2312 * argument of zero. Trailing empty strings are therefore not included in
2313 * the resulting array.
2315 * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the following
2316 * results with these expressions:
2318 * <blockquote><table cellpadding=1 cellspacing=0 summary="Split examples showing regex and result">
2323 * <tr><td align=center>:</td>
2324 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2325 * <tr><td align=center>o</td>
2326 * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
2327 * </table></blockquote>
2331 * the delimiting regular expression
2333 * @return the array of strings computed by splitting this string
2334 * around matches of the given regular expression
2336 * @throws PatternSyntaxException
2337 * if the regular expression's syntax is invalid
2339 * @see java.util.regex.Pattern
2344 public String[] split(String regex) {
2345 return split(regex, 0);
2349 * Converts all of the characters in this <code>String</code> to lower
2350 * case using the rules of the given <code>Locale</code>. Case mapping is based
2351 * on the Unicode Standard version specified by the {@link java.lang.Character Character}
2352 * class. Since case mappings are not always 1:1 char mappings, the resulting
2353 * <code>String</code> may be a different length than the original <code>String</code>.
2355 * Examples of lowercase mappings are in the following table:
2356 * <table border="1" summary="Lowercase mapping examples showing language code of locale, upper case, lower case, and description">
2358 * <th>Language Code of Locale</th>
2359 * <th>Upper Case</th>
2360 * <th>Lower Case</th>
2361 * <th>Description</th>
2364 * <td>tr (Turkish)</td>
2365 * <td>\u0130</td>
2366 * <td>\u0069</td>
2367 * <td>capital letter I with dot above -> small letter i</td>
2370 * <td>tr (Turkish)</td>
2371 * <td>\u0049</td>
2372 * <td>\u0131</td>
2373 * <td>capital letter I -> small letter dotless i </td>
2377 * <td>French Fries</td>
2378 * <td>french fries</td>
2379 * <td>lowercased all chars in String</td>
2383 * <td><img src="doc-files/capiota.gif" alt="capiota"><img src="doc-files/capchi.gif" alt="capchi">
2384 * <img src="doc-files/captheta.gif" alt="captheta"><img src="doc-files/capupsil.gif" alt="capupsil">
2385 * <img src="doc-files/capsigma.gif" alt="capsigma"></td>
2386 * <td><img src="doc-files/iota.gif" alt="iota"><img src="doc-files/chi.gif" alt="chi">
2387 * <img src="doc-files/theta.gif" alt="theta"><img src="doc-files/upsilon.gif" alt="upsilon">
2388 * <img src="doc-files/sigma1.gif" alt="sigma"></td>
2389 * <td>lowercased all chars in String</td>
2393 * @param locale use the case transformation rules for this locale
2394 * @return the <code>String</code>, converted to lowercase.
2395 * @see java.lang.String#toLowerCase()
2396 * @see java.lang.String#toUpperCase()
2397 * @see java.lang.String#toUpperCase(Locale)
2400 // public String toLowerCase(Locale locale) {
2401 // if (locale == null) {
2402 // throw new NullPointerException();
2407 // /* Now check if there are any characters that need to be changed. */
2409 // for (firstUpper = 0 ; firstUpper < count; ) {
2410 // char c = value[offset+firstUpper];
2411 // if ((c >= Character.MIN_HIGH_SURROGATE) &&
2412 // (c <= Character.MAX_HIGH_SURROGATE)) {
2413 // int supplChar = codePointAt(firstUpper);
2414 // if (supplChar != Character.toLowerCase(supplChar)) {
2417 // firstUpper += Character.charCount(supplChar);
2419 // if (c != Character.toLowerCase(c)) {
2428 // char[] result = new char[count];
2429 // int resultOffset = 0; /* result may grow, so i+resultOffset
2430 // * is the write location in result */
2432 // /* Just copy the first few lowerCase characters. */
2433 // System.arraycopy(value, offset, result, 0, firstUpper);
2435 // String lang = locale.getLanguage();
2436 // boolean localeDependent =
2437 // (lang == "tr" || lang == "az" || lang == "lt");
2438 // char[] lowerCharArray;
2442 // for (int i = firstUpper; i < count; i += srcCount) {
2443 // srcChar = (int)value[offset+i];
2444 // if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
2445 // (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
2446 // srcChar = codePointAt(i);
2447 // srcCount = Character.charCount(srcChar);
2451 // if (localeDependent || srcChar == '\u03A3') { // GREEK CAPITAL LETTER SIGMA
2452 // lowerChar = ConditionalSpecialCasing.toLowerCaseEx(this, i, locale);
2453 // } else if (srcChar == '\u0130') { // LATIN CAPITAL LETTER I DOT
2454 // lowerChar = Character.ERROR;
2456 // lowerChar = Character.toLowerCase(srcChar);
2458 // if ((lowerChar == Character.ERROR) ||
2459 // (lowerChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
2460 // if (lowerChar == Character.ERROR) {
2461 // if (!localeDependent && srcChar == '\u0130') {
2463 // ConditionalSpecialCasing.toLowerCaseCharArray(this, i, Locale.ENGLISH);
2466 // ConditionalSpecialCasing.toLowerCaseCharArray(this, i, locale);
2468 // } else if (srcCount == 2) {
2469 // resultOffset += Character.toChars(lowerChar, result, i + resultOffset) - srcCount;
2472 // lowerCharArray = Character.toChars(lowerChar);
2475 // /* Grow result if needed */
2476 // int mapLen = lowerCharArray.length;
2477 // if (mapLen > srcCount) {
2478 // char[] result2 = new char[result.length + mapLen - srcCount];
2479 // System.arraycopy(result, 0, result2, 0,
2480 // i + resultOffset);
2481 // result = result2;
2483 // for (int x=0; x<mapLen; ++x) {
2484 // result[i+resultOffset+x] = lowerCharArray[x];
2486 // resultOffset += (mapLen - srcCount);
2488 // result[i+resultOffset] = (char)lowerChar;
2491 // return new String(0, count+resultOffset, result);
2495 * Converts all of the characters in this <code>String</code> to lower
2496 * case using the rules of the default locale. This is equivalent to calling
2497 * <code>toLowerCase(Locale.getDefault())</code>.
2499 * <b>Note:</b> This method is locale sensitive, and may produce unexpected
2500 * results if used for strings that are intended to be interpreted locale
2502 * Examples are programming language identifiers, protocol keys, and HTML
2504 * For instance, <code>"TITLE".toLowerCase()</code> in a Turkish locale
2505 * returns <code>"t\u005Cu0131tle"</code>, where '\u005Cu0131' is the
2506 * LATIN SMALL LETTER DOTLESS I character.
2507 * To obtain correct results for locale insensitive strings, use
2508 * <code>toLowerCase(Locale.ENGLISH)</code>.
2510 * @return the <code>String</code>, converted to lowercase.
2511 * @see java.lang.String#toLowerCase(Locale)
2513 @JavaScriptBody(args = {}, body = "return this.toLowerCase();")
2514 public String toLowerCase() {
2515 throw new UnsupportedOperationException("Should be supported but without connection to locale");
2519 * Converts all of the characters in this <code>String</code> to upper
2520 * case using the rules of the given <code>Locale</code>. Case mapping is based
2521 * on the Unicode Standard version specified by the {@link java.lang.Character Character}
2522 * class. Since case mappings are not always 1:1 char mappings, the resulting
2523 * <code>String</code> may be a different length than the original <code>String</code>.
2525 * Examples of locale-sensitive and 1:M case mappings are in the following table.
2527 * <table border="1" summary="Examples of locale-sensitive and 1:M case mappings. Shows Language code of locale, lower case, upper case, and description.">
2529 * <th>Language Code of Locale</th>
2530 * <th>Lower Case</th>
2531 * <th>Upper Case</th>
2532 * <th>Description</th>
2535 * <td>tr (Turkish)</td>
2536 * <td>\u0069</td>
2537 * <td>\u0130</td>
2538 * <td>small letter i -> capital letter I with dot above</td>
2541 * <td>tr (Turkish)</td>
2542 * <td>\u0131</td>
2543 * <td>\u0049</td>
2544 * <td>small letter dotless i -> capital letter I</td>
2548 * <td>\u00df</td>
2549 * <td>\u0053 \u0053</td>
2550 * <td>small letter sharp s -> two letters: SS</td>
2554 * <td>Fahrvergnügen</td>
2555 * <td>FAHRVERGNÜGEN</td>
2559 * @param locale use the case transformation rules for this locale
2560 * @return the <code>String</code>, converted to uppercase.
2561 * @see java.lang.String#toUpperCase()
2562 * @see java.lang.String#toLowerCase()
2563 * @see java.lang.String#toLowerCase(Locale)
2566 /* not for javascript
2567 public String toUpperCase(Locale locale) {
2568 if (locale == null) {
2569 throw new NullPointerException();
2574 // Now check if there are any characters that need to be changed.
2576 for (firstLower = 0 ; firstLower < count; ) {
2577 int c = (int)value[offset+firstLower];
2579 if ((c >= Character.MIN_HIGH_SURROGATE) &&
2580 (c <= Character.MAX_HIGH_SURROGATE)) {
2581 c = codePointAt(firstLower);
2582 srcCount = Character.charCount(c);
2586 int upperCaseChar = Character.toUpperCaseEx(c);
2587 if ((upperCaseChar == Character.ERROR) ||
2588 (c != upperCaseChar)) {
2591 firstLower += srcCount;
2596 char[] result = new char[count]; /* may grow *
2597 int resultOffset = 0; /* result may grow, so i+resultOffset
2598 * is the write location in result *
2600 /* Just copy the first few upperCase characters. *
2601 System.arraycopy(value, offset, result, 0, firstLower);
2603 String lang = locale.getLanguage();
2604 boolean localeDependent =
2605 (lang == "tr" || lang == "az" || lang == "lt");
2606 char[] upperCharArray;
2610 for (int i = firstLower; i < count; i += srcCount) {
2611 srcChar = (int)value[offset+i];
2612 if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
2613 (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
2614 srcChar = codePointAt(i);
2615 srcCount = Character.charCount(srcChar);
2619 if (localeDependent) {
2620 upperChar = ConditionalSpecialCasing.toUpperCaseEx(this, i, locale);
2622 upperChar = Character.toUpperCaseEx(srcChar);
2624 if ((upperChar == Character.ERROR) ||
2625 (upperChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
2626 if (upperChar == Character.ERROR) {
2627 if (localeDependent) {
2629 ConditionalSpecialCasing.toUpperCaseCharArray(this, i, locale);
2631 upperCharArray = Character.toUpperCaseCharArray(srcChar);
2633 } else if (srcCount == 2) {
2634 resultOffset += Character.toChars(upperChar, result, i + resultOffset) - srcCount;
2637 upperCharArray = Character.toChars(upperChar);
2640 /* Grow result if needed *
2641 int mapLen = upperCharArray.length;
2642 if (mapLen > srcCount) {
2643 char[] result2 = new char[result.length + mapLen - srcCount];
2644 System.arraycopy(result, 0, result2, 0,
2648 for (int x=0; x<mapLen; ++x) {
2649 result[i+resultOffset+x] = upperCharArray[x];
2651 resultOffset += (mapLen - srcCount);
2653 result[i+resultOffset] = (char)upperChar;
2656 return new String(0, count+resultOffset, result);
2661 * Converts all of the characters in this <code>String</code> to upper
2662 * case using the rules of the default locale. This method is equivalent to
2663 * <code>toUpperCase(Locale.getDefault())</code>.
2665 * <b>Note:</b> This method is locale sensitive, and may produce unexpected
2666 * results if used for strings that are intended to be interpreted locale
2668 * Examples are programming language identifiers, protocol keys, and HTML
2670 * For instance, <code>"title".toUpperCase()</code> in a Turkish locale
2671 * returns <code>"T\u005Cu0130TLE"</code>, where '\u005Cu0130' is the
2672 * LATIN CAPITAL LETTER I WITH DOT ABOVE character.
2673 * To obtain correct results for locale insensitive strings, use
2674 * <code>toUpperCase(Locale.ENGLISH)</code>.
2676 * @return the <code>String</code>, converted to uppercase.
2677 * @see java.lang.String#toUpperCase(Locale)
2679 @JavaScriptBody(args = {}, body = "return this.toUpperCase();")
2680 public String toUpperCase() {
2681 throw new UnsupportedOperationException();
2685 * Returns a copy of the string, with leading and trailing whitespace
2688 * If this <code>String</code> object represents an empty character
2689 * sequence, or the first and last characters of character sequence
2690 * represented by this <code>String</code> object both have codes
2691 * greater than <code>'\u0020'</code> (the space character), then a
2692 * reference to this <code>String</code> object is returned.
2694 * Otherwise, if there is no character with a code greater than
2695 * <code>'\u0020'</code> in the string, then a new
2696 * <code>String</code> object representing an empty string is created
2699 * Otherwise, let <i>k</i> be the index of the first character in the
2700 * string whose code is greater than <code>'\u0020'</code>, and let
2701 * <i>m</i> be the index of the last character in the string whose code
2702 * is greater than <code>'\u0020'</code>. A new <code>String</code>
2703 * object is created, representing the substring of this string that
2704 * begins with the character at index <i>k</i> and ends with the
2705 * character at index <i>m</i>-that is, the result of
2706 * <code>this.substring(<i>k</i>, <i>m</i>+1)</code>.
2708 * This method may be used to trim whitespace (as defined above) from
2709 * the beginning and end of a string.
2711 * @return A copy of this string with leading and trailing white
2712 * space removed, or this string if it has no leading or
2713 * trailing white space.
2715 public String trim() {
2718 int off = offset(); /* avoid getfield opcode */
2719 char[] val = toCharArray(); /* avoid getfield opcode */
2721 while ((st < len) && (val[off + st] <= ' ')) {
2724 while ((st < len) && (val[off + len - 1] <= ' ')) {
2727 return ((st > 0) || (len < length())) ? substring(st, len) : this;
2731 * This object (which is already a string!) is itself returned.
2733 * @return the string itself.
2735 @JavaScriptBody(args = {}, body = "return this.toString();")
2736 public String toString() {
2741 * Converts this string to a new character array.
2743 * @return a newly allocated character array whose length is the length
2744 * of this string and whose contents are initialized to contain
2745 * the character sequence represented by this string.
2747 public char[] toCharArray() {
2748 char result[] = new char[length()];
2749 getChars(0, length(), result, 0);
2754 * Returns a formatted string using the specified format string and
2757 * <p> The locale always used is the one returned by {@link
2758 * java.util.Locale#getDefault() Locale.getDefault()}.
2761 * A <a href="../util/Formatter.html#syntax">format string</a>
2764 * Arguments referenced by the format specifiers in the format
2765 * string. If there are more arguments than format specifiers, the
2766 * extra arguments are ignored. The number of arguments is
2767 * variable and may be zero. The maximum number of arguments is
2768 * limited by the maximum dimension of a Java array as defined by
2769 * <cite>The Java™ Virtual Machine Specification</cite>.
2770 * The behaviour on a
2771 * <tt>null</tt> argument depends on the <a
2772 * href="../util/Formatter.html#syntax">conversion</a>.
2774 * @throws IllegalFormatException
2775 * If a format string contains an illegal syntax, a format
2776 * specifier that is incompatible with the given arguments,
2777 * insufficient arguments given the format string, or other
2778 * illegal conditions. For specification of all possible
2779 * formatting errors, see the <a
2780 * href="../util/Formatter.html#detail">Details</a> section of the
2781 * formatter class specification.
2783 * @throws NullPointerException
2784 * If the <tt>format</tt> is <tt>null</tt>
2786 * @return A formatted string
2788 * @see java.util.Formatter
2791 public static String format(String format, Object ... args) {
2792 throw new UnsupportedOperationException();
2796 * Returns a formatted string using the specified locale, format string,
2800 * The {@linkplain java.util.Locale locale} to apply during
2801 * formatting. If <tt>l</tt> is <tt>null</tt> then no localization
2805 * A <a href="../util/Formatter.html#syntax">format string</a>
2808 * Arguments referenced by the format specifiers in the format
2809 * string. If there are more arguments than format specifiers, the
2810 * extra arguments are ignored. The number of arguments is
2811 * variable and may be zero. The maximum number of arguments is
2812 * limited by the maximum dimension of a Java array as defined by
2813 * <cite>The Java™ Virtual Machine Specification</cite>.
2814 * The behaviour on a
2815 * <tt>null</tt> argument depends on the <a
2816 * href="../util/Formatter.html#syntax">conversion</a>.
2818 * @throws IllegalFormatException
2819 * If a format string contains an illegal syntax, a format
2820 * specifier that is incompatible with the given arguments,
2821 * insufficient arguments given the format string, or other
2822 * illegal conditions. For specification of all possible
2823 * formatting errors, see the <a
2824 * href="../util/Formatter.html#detail">Details</a> section of the
2825 * formatter class specification
2827 * @throws NullPointerException
2828 * If the <tt>format</tt> is <tt>null</tt>
2830 * @return A formatted string
2832 * @see java.util.Formatter
2835 // public static String format(Locale l, String format, Object ... args) {
2836 // return new Formatter(l).format(format, args).toString();
2840 * Returns the string representation of the <code>Object</code> argument.
2842 * @param obj an <code>Object</code>.
2843 * @return if the argument is <code>null</code>, then a string equal to
2844 * <code>"null"</code>; otherwise, the value of
2845 * <code>obj.toString()</code> is returned.
2846 * @see java.lang.Object#toString()
2848 public static String valueOf(Object obj) {
2849 return (obj == null) ? "null" : obj.toString();
2853 * Returns the string representation of the <code>char</code> array
2854 * argument. The contents of the character array are copied; subsequent
2855 * modification of the character array does not affect the newly
2858 * @param data a <code>char</code> array.
2859 * @return a newly allocated string representing the same sequence of
2860 * characters contained in the character array argument.
2862 public static String valueOf(char data[]) {
2863 return new String(data);
2867 * Returns the string representation of a specific subarray of the
2868 * <code>char</code> array argument.
2870 * The <code>offset</code> argument is the index of the first
2871 * character of the subarray. The <code>count</code> argument
2872 * specifies the length of the subarray. The contents of the subarray
2873 * are copied; subsequent modification of the character array does not
2874 * affect the newly created string.
2876 * @param data the character array.
2877 * @param offset the initial offset into the value of the
2878 * <code>String</code>.
2879 * @param count the length of the value of the <code>String</code>.
2880 * @return a string representing the sequence of characters contained
2881 * in the subarray of the character array argument.
2882 * @exception IndexOutOfBoundsException if <code>offset</code> is
2883 * negative, or <code>count</code> is negative, or
2884 * <code>offset+count</code> is larger than
2885 * <code>data.length</code>.
2887 public static String valueOf(char data[], int offset, int count) {
2888 return new String(data, offset, count);
2892 * Returns a String that represents the character sequence in the
2895 * @param data the character array.
2896 * @param offset initial offset of the subarray.
2897 * @param count length of the subarray.
2898 * @return a <code>String</code> that contains the characters of the
2899 * specified subarray of the character array.
2901 public static String copyValueOf(char data[], int offset, int count) {
2902 // All public String constructors now copy the data.
2903 return new String(data, offset, count);
2907 * Returns a String that represents the character sequence in the
2910 * @param data the character array.
2911 * @return a <code>String</code> that contains the characters of the
2914 public static String copyValueOf(char data[]) {
2915 return copyValueOf(data, 0, data.length);
2919 * Returns the string representation of the <code>boolean</code> argument.
2921 * @param b a <code>boolean</code>.
2922 * @return if the argument is <code>true</code>, a string equal to
2923 * <code>"true"</code> is returned; otherwise, a string equal to
2924 * <code>"false"</code> is returned.
2926 public static String valueOf(boolean b) {
2927 return b ? "true" : "false";
2931 * Returns the string representation of the <code>char</code>
2934 * @param c a <code>char</code>.
2935 * @return a string of length <code>1</code> containing
2936 * as its single character the argument <code>c</code>.
2938 public static String valueOf(char c) {
2940 return new String(data, 0, 1);
2944 * Returns the string representation of the <code>int</code> argument.
2946 * The representation is exactly the one returned by the
2947 * <code>Integer.toString</code> method of one argument.
2949 * @param i an <code>int</code>.
2950 * @return a string representation of the <code>int</code> argument.
2951 * @see java.lang.Integer#toString(int, int)
2953 public static String valueOf(int i) {
2954 return Integer.toString(i);
2958 * Returns the string representation of the <code>long</code> argument.
2960 * The representation is exactly the one returned by the
2961 * <code>Long.toString</code> method of one argument.
2963 * @param l a <code>long</code>.
2964 * @return a string representation of the <code>long</code> argument.
2965 * @see java.lang.Long#toString(long)
2967 public static String valueOf(long l) {
2968 return Long.toString(l);
2972 * Returns the string representation of the <code>float</code> argument.
2974 * The representation is exactly the one returned by the
2975 * <code>Float.toString</code> method of one argument.
2977 * @param f a <code>float</code>.
2978 * @return a string representation of the <code>float</code> argument.
2979 * @see java.lang.Float#toString(float)
2981 public static String valueOf(float f) {
2982 return Float.toString(f);
2986 * Returns the string representation of the <code>double</code> argument.
2988 * The representation is exactly the one returned by the
2989 * <code>Double.toString</code> method of one argument.
2991 * @param d a <code>double</code>.
2992 * @return a string representation of the <code>double</code> argument.
2993 * @see java.lang.Double#toString(double)
2995 public static String valueOf(double d) {
2996 return Double.toString(d);
3000 * Returns a canonical representation for the string object.
3002 * A pool of strings, initially empty, is maintained privately by the
3003 * class <code>String</code>.
3005 * When the intern method is invoked, if the pool already contains a
3006 * string equal to this <code>String</code> object as determined by
3007 * the {@link #equals(Object)} method, then the string from the pool is
3008 * returned. Otherwise, this <code>String</code> object is added to the
3009 * pool and a reference to this <code>String</code> object is returned.
3011 * It follows that for any two strings <code>s</code> and <code>t</code>,
3012 * <code>s.intern() == t.intern()</code> is <code>true</code>
3013 * if and only if <code>s.equals(t)</code> is <code>true</code>.
3015 * All literal strings and string-valued constant expressions are
3016 * interned. String literals are defined in section 3.10.5 of the
3017 * <cite>The Java™ Language Specification</cite>.
3019 * @return a string that has the same contents as this string, but is
3020 * guaranteed to be from a pool of unique strings.
3022 public native String intern();
3025 private static <T> T checkUTF8(T data, String charsetName)
3026 throws UnsupportedEncodingException {
3027 if (charsetName == null) {
3028 throw new NullPointerException("charsetName");
3030 if (!charsetName.equalsIgnoreCase("UTF-8")
3031 && !charsetName.equalsIgnoreCase("UTF8")) {
3032 throw new UnsupportedEncodingException(charsetName);
3037 private static int nextChar(byte[] arr, int[] index) throws IndexOutOfBoundsException {
3038 int c = arr[index[0]++] & 0xff;
3052 /* 110x xxxx 10xx xxxx*/
3053 int char2 = (int) arr[index[0]++];
3054 if ((char2 & 0xC0) != 0x80) {
3055 throw new IndexOutOfBoundsException("malformed input");
3057 return (((c & 0x1F) << 6) | (char2 & 0x3F));
3060 /* 1110 xxxx 10xx xxxx 10xx xxxx */
3061 int char2 = arr[index[0]++];
3062 int char3 = arr[index[0]++];
3063 if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80)) {
3064 throw new IndexOutOfBoundsException("malformed input");
3066 return (((c & 0x0F) << 12)
3067 | ((char2 & 0x3F) << 6)
3068 | ((char3 & 0x3F) << 0));
3071 /* 10xx xxxx, 1111 xxxx */
3072 throw new IndexOutOfBoundsException("malformed input");