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.util.Comparator;
29 import org.apidesign.bck2brwsr.core.ExtraJavaScript;
30 import org.apidesign.bck2brwsr.core.JavaScriptBody;
31 import org.apidesign.bck2brwsr.core.JavaScriptOnly;
32 import org.apidesign.bck2brwsr.core.JavaScriptPrototype;
33 import org.apidesign.bck2brwsr.emul.lang.System;
36 * The <code>String</code> class represents character strings. All
37 * string literals in Java programs, such as <code>"abc"</code>, are
38 * implemented as instances of this class.
40 * Strings are constant; their values cannot be changed after they
41 * are created. String buffers support mutable strings.
42 * Because String objects are immutable they can be shared. For example:
43 * <p><blockquote><pre>
45 * </pre></blockquote><p>
47 * <p><blockquote><pre>
48 * char data[] = {'a', 'b', 'c'};
49 * String str = new String(data);
50 * </pre></blockquote><p>
51 * Here are some more examples of how strings can be used:
52 * <p><blockquote><pre>
53 * System.out.println("abc");
55 * System.out.println("abc" + cde);
56 * String c = "abc".substring(2,3);
57 * String d = cde.substring(1, 2);
60 * The class <code>String</code> includes methods for examining
61 * individual characters of the sequence, for comparing strings, for
62 * searching strings, for extracting substrings, and for creating a
63 * copy of a string with all characters translated to uppercase or to
64 * lowercase. Case mapping is based on the Unicode Standard version
65 * specified by the {@link java.lang.Character Character} class.
67 * The Java language provides special support for the string
68 * concatenation operator ( + ), and for conversion of
69 * other objects to strings. String concatenation is implemented
70 * through the <code>StringBuilder</code>(or <code>StringBuffer</code>)
71 * class and its <code>append</code> method.
72 * String conversions are implemented through the method
73 * <code>toString</code>, defined by <code>Object</code> and
74 * inherited by all classes in Java. For additional information on
75 * string concatenation and conversion, see Gosling, Joy, and Steele,
76 * <i>The Java Language Specification</i>.
78 * <p> Unless otherwise noted, passing a <tt>null</tt> argument to a constructor
79 * or method in this class will cause a {@link NullPointerException} to be
82 * <p>A <code>String</code> represents a string in the UTF-16 format
83 * in which <em>supplementary characters</em> are represented by <em>surrogate
84 * pairs</em> (see the section <a href="Character.html#unicode">Unicode
85 * Character Representations</a> in the <code>Character</code> class for
87 * Index values refer to <code>char</code> code units, so a supplementary
88 * character uses two positions in a <code>String</code>.
89 * <p>The <code>String</code> class provides methods for dealing with
90 * Unicode code points (i.e., characters), in addition to those for
91 * dealing with Unicode code units (i.e., <code>char</code> values).
94 * @author Arthur van Hoff
95 * @author Martin Buchholz
97 * @see java.lang.Object#toString()
98 * @see java.lang.StringBuffer
99 * @see java.lang.StringBuilder
100 * @see java.nio.charset.Charset
105 resource="/org/apidesign/vm4brwsr/emul/lang/java_lang_String.js",
108 @JavaScriptPrototype(container = "String.prototype", prototype = "new String")
109 public final class String
110 implements java.io.Serializable, Comparable<String>, CharSequence
112 /** real string to delegate to */
115 /** use serialVersionUID from JDK 1.0.2 for interoperability */
116 private static final long serialVersionUID = -6849794470754667710L;
118 @JavaScriptOnly(name="toString", value="String.prototype._r")
119 private static void jsToString() {
122 @JavaScriptOnly(name="valueOf", value="function() { return this.toString().valueOf(); }")
123 private static void jsValudOf() {
127 * Class String is special cased within the Serialization Stream Protocol.
129 * A String instance is written initially into an ObjectOutputStream in the
132 * <code>TC_STRING</code> (utf String)
134 * The String is written by method <code>DataOutput.writeUTF</code>.
135 * A new handle is generated to refer to all future references to the
136 * string instance within the stream.
138 // private static final ObjectStreamField[] serialPersistentFields =
139 // new ObjectStreamField[0];
142 * Initializes a newly created {@code String} object so that it represents
143 * an empty character sequence. Note that use of this constructor is
144 * unnecessary since Strings are immutable.
151 * Initializes a newly created {@code String} object so that it represents
152 * the same sequence of characters as the argument; in other words, the
153 * newly created string is a copy of the argument string. Unless an
154 * explicit copy of {@code original} is needed, use of this constructor is
155 * unnecessary since Strings are immutable.
160 public String(String original) {
161 this.r = original.toString();
165 * Allocates a new {@code String} so that it represents the sequence of
166 * characters currently contained in the character array argument. The
167 * contents of the character array are copied; subsequent modification of
168 * the character array does not affect the newly created string.
171 * The initial value of the string
173 @JavaScriptBody(args = { "charArr" }, body=
174 "for (var i = 0; i < charArr.length; i++) {\n"
175 + " if (typeof charArr[i] === 'number') charArr[i] = String.fromCharCode(charArr[i]);\n"
177 + "this._r(charArr.join(''));\n"
179 public String(char value[]) {
183 * Allocates a new {@code String} that contains characters from a subarray
184 * of the character array argument. The {@code offset} argument is the
185 * index of the first character of the subarray and the {@code count}
186 * argument specifies the length of the subarray. The contents of the
187 * subarray are copied; subsequent modification of the character array does
188 * not affect the newly created string.
191 * Array that is the source of characters
199 * @throws IndexOutOfBoundsException
200 * If the {@code offset} and {@code count} arguments index
201 * characters outside the bounds of the {@code value} array
203 @JavaScriptBody(args = { "charArr", "off", "cnt" }, body =
204 "var up = off + cnt;\n" +
205 "for (var i = off; i < up; i++) {\n" +
206 " if (typeof charArr[i] === 'number') charArr[i] = String.fromCharCode(charArr[i]);\n" +
208 "this._r(charArr.slice(off, up).join(\"\"));\n"
210 public String(char value[], int offset, int count) {
214 * Allocates a new {@code String} that contains characters from a subarray
215 * of the <a href="Character.html#unicode">Unicode code point</a> array
216 * argument. The {@code offset} argument is the index of the first code
217 * point of the subarray and the {@code count} argument specifies the
218 * length of the subarray. The contents of the subarray are converted to
219 * {@code char}s; subsequent modification of the {@code int} array does not
220 * affect the newly created string.
223 * Array that is the source of Unicode code points
231 * @throws IllegalArgumentException
232 * If any invalid Unicode code point is found in {@code
235 * @throws IndexOutOfBoundsException
236 * If the {@code offset} and {@code count} arguments index
237 * characters outside the bounds of the {@code codePoints} array
241 public String(int[] codePoints, int offset, int count) {
243 throw new StringIndexOutOfBoundsException(offset);
246 throw new StringIndexOutOfBoundsException(count);
248 // Note: offset or count might be near -1>>>1.
249 if (offset > codePoints.length - count) {
250 throw new StringIndexOutOfBoundsException(offset + count);
253 final int end = offset + count;
255 // Pass 1: Compute precise size of char[]
257 for (int i = offset; i < end; i++) {
258 int c = codePoints[i];
259 if (Character.isBmpCodePoint(c))
261 else if (Character.isValidCodePoint(c))
263 else throw new IllegalArgumentException(Integer.toString(c));
266 // Pass 2: Allocate and fill in char[]
267 final char[] v = new char[n];
269 for (int i = offset, j = 0; i < end; i++, j++) {
270 int c = codePoints[i];
271 if (Character.isBmpCodePoint(c))
274 Character.toSurrogates(c, v, j++);
277 this.r = new String(v, 0, n);
281 * Allocates a new {@code String} constructed from a subarray of an array
282 * of 8-bit integer values.
284 * <p> The {@code offset} argument is the index of the first byte of the
285 * subarray, and the {@code count} argument specifies the length of the
288 * <p> Each {@code byte} in the subarray is converted to a {@code char} as
289 * specified in the method above.
291 * @deprecated This method does not properly convert bytes into characters.
292 * As of JDK 1.1, the preferred way to do this is via the
293 * {@code String} constructors that take a {@link
294 * java.nio.charset.Charset}, charset name, or that use the platform's
298 * The bytes to be converted to characters
301 * The top 8 bits of each 16-bit Unicode code unit
308 * @throws IndexOutOfBoundsException
309 * If the {@code offset} or {@code count} argument is invalid
311 * @see #String(byte[], int)
312 * @see #String(byte[], int, int, java.lang.String)
313 * @see #String(byte[], int, int, java.nio.charset.Charset)
314 * @see #String(byte[], int, int)
315 * @see #String(byte[], java.lang.String)
316 * @see #String(byte[], java.nio.charset.Charset)
317 * @see #String(byte[])
320 public String(byte ascii[], int hibyte, int offset, int count) {
321 checkBounds(ascii, offset, count);
322 char value[] = new char[count];
325 for (int i = count ; i-- > 0 ;) {
326 value[i] = (char) (ascii[i + offset] & 0xff);
330 for (int i = count ; i-- > 0 ;) {
331 value[i] = (char) (hibyte | (ascii[i + offset] & 0xff));
334 this.r = new String(value, 0, count);
338 * Allocates a new {@code String} containing characters constructed from
339 * an array of 8-bit integer values. Each character <i>c</i>in the
340 * resulting string is constructed from the corresponding component
341 * <i>b</i> in the byte array such that:
344 * <b><i>c</i></b> == (char)(((hibyte & 0xff) << 8)
345 * | (<b><i>b</i></b> & 0xff))
346 * </pre></blockquote>
348 * @deprecated This method does not properly convert bytes into
349 * characters. As of JDK 1.1, the preferred way to do this is via the
350 * {@code String} constructors that take a {@link
351 * java.nio.charset.Charset}, charset name, or that use the platform's
355 * The bytes to be converted to characters
358 * The top 8 bits of each 16-bit Unicode code unit
360 * @see #String(byte[], int, int, java.lang.String)
361 * @see #String(byte[], int, int, java.nio.charset.Charset)
362 * @see #String(byte[], int, int)
363 * @see #String(byte[], java.lang.String)
364 * @see #String(byte[], java.nio.charset.Charset)
365 * @see #String(byte[])
368 public String(byte ascii[], int hibyte) {
369 this(ascii, hibyte, 0, ascii.length);
372 /* Common private utility method used to bounds check the byte array
373 * and requested offset & length values used by the String(byte[],..)
376 private static void checkBounds(byte[] bytes, int offset, int length) {
378 throw new StringIndexOutOfBoundsException(length);
380 throw new StringIndexOutOfBoundsException(offset);
381 if (offset > bytes.length - length)
382 throw new StringIndexOutOfBoundsException(offset + length);
386 * Constructs a new {@code String} by decoding the specified subarray of
387 * bytes using the specified charset. The length of the new {@code String}
388 * is a function of the charset, and hence may not be equal to the length
391 * <p> The behavior of this constructor when the given bytes are not valid
392 * in the given charset is unspecified. The {@link
393 * java.nio.charset.CharsetDecoder} class should be used when more control
394 * over the decoding process is required.
397 * The bytes to be decoded into characters
400 * The index of the first byte to decode
403 * The number of bytes to decode
406 * The name of a supported {@linkplain java.nio.charset.Charset
409 * @throws UnsupportedEncodingException
410 * If the named charset is not supported
412 * @throws IndexOutOfBoundsException
413 * If the {@code offset} and {@code length} arguments index
414 * characters outside the bounds of the {@code bytes} array
418 // public String(byte bytes[], int offset, int length, String charsetName)
419 // throws UnsupportedEncodingException
421 // if (charsetName == null)
422 // throw new NullPointerException("charsetName");
423 // checkBounds(bytes, offset, length);
424 // char[] v = StringCoding.decode(charsetName, bytes, offset, length);
426 // this.count = v.length;
431 * Constructs a new {@code String} by decoding the specified subarray of
432 * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
433 * The length of the new {@code String} is a function of the charset, and
434 * hence may not be equal to the length of the subarray.
436 * <p> This method always replaces malformed-input and unmappable-character
437 * sequences with this charset's default replacement string. The {@link
438 * java.nio.charset.CharsetDecoder} class should be used when more control
439 * over the decoding process is required.
442 * The bytes to be decoded into characters
445 * The index of the first byte to decode
448 * The number of bytes to decode
451 * The {@linkplain java.nio.charset.Charset charset} to be used to
452 * decode the {@code bytes}
454 * @throws IndexOutOfBoundsException
455 * If the {@code offset} and {@code length} arguments index
456 * characters outside the bounds of the {@code bytes} array
460 /* don't want dependnecy on Charset
461 public String(byte bytes[], int offset, int length, Charset charset) {
463 throw new NullPointerException("charset");
464 checkBounds(bytes, offset, length);
465 char[] v = StringCoding.decode(charset, bytes, offset, length);
467 this.count = v.length;
473 * Constructs a new {@code String} by decoding the specified array of bytes
474 * using the specified {@linkplain java.nio.charset.Charset charset}. The
475 * length of the new {@code String} is a function of the charset, and hence
476 * may not be equal to the length of the byte array.
478 * <p> The behavior of this constructor when the given bytes are not valid
479 * in the given charset is unspecified. The {@link
480 * java.nio.charset.CharsetDecoder} class should be used when more control
481 * over the decoding process is required.
484 * The bytes to be decoded into characters
487 * The name of a supported {@linkplain java.nio.charset.Charset
490 * @throws UnsupportedEncodingException
491 * If the named charset is not supported
495 // public String(byte bytes[], String charsetName)
496 // throws UnsupportedEncodingException
498 // this(bytes, 0, bytes.length, charsetName);
502 * Constructs a new {@code String} by decoding the specified array of
503 * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
504 * The length of the new {@code String} is a function of the charset, and
505 * hence may not be equal to the length of the byte array.
507 * <p> This method always replaces malformed-input and unmappable-character
508 * sequences with this charset's default replacement string. The {@link
509 * java.nio.charset.CharsetDecoder} class should be used when more control
510 * over the decoding process is required.
513 * The bytes to be decoded into characters
516 * The {@linkplain java.nio.charset.Charset charset} to be used to
517 * decode the {@code bytes}
521 /* don't want dep on Charset
522 public String(byte bytes[], Charset charset) {
523 this(bytes, 0, bytes.length, charset);
528 * Constructs a new {@code String} by decoding the specified subarray of
529 * bytes using the platform's default charset. The length of the new
530 * {@code String} is a function of the charset, and hence may not be equal
531 * to the length of the subarray.
533 * <p> The behavior of this constructor when the given bytes are not valid
534 * in the default charset is unspecified. The {@link
535 * java.nio.charset.CharsetDecoder} class should be used when more control
536 * over the decoding process is required.
539 * The bytes to be decoded into characters
542 * The index of the first byte to decode
545 * The number of bytes to decode
547 * @throws IndexOutOfBoundsException
548 * If the {@code offset} and the {@code length} arguments index
549 * characters outside the bounds of the {@code bytes} array
553 public String(byte bytes[], int offset, int length) {
554 checkBounds(bytes, offset, length);
555 char[] v = new char[length];
556 for (int i = 0; i < length; i++) {
557 v[i] = (char)bytes[offset++];
559 this.r = new String(v, 0, v.length);
563 * Constructs a new {@code String} by decoding the specified array of bytes
564 * using the platform's default charset. The length of the new {@code
565 * String} is a function of the charset, and hence may not be equal to the
566 * length of the byte array.
568 * <p> The behavior of this constructor when the given bytes are not valid
569 * in the default charset is unspecified. The {@link
570 * java.nio.charset.CharsetDecoder} class should be used when more control
571 * over the decoding process is required.
574 * The bytes to be decoded into characters
578 public String(byte bytes[]) {
579 this(bytes, 0, bytes.length);
583 * Allocates a new string that contains the sequence of characters
584 * currently contained in the string buffer argument. The contents of the
585 * string buffer are copied; subsequent modification of the string buffer
586 * does not affect the newly created string.
589 * A {@code StringBuffer}
591 public String(StringBuffer buffer) {
592 this.r = buffer.toString();
596 * Allocates a new string that contains the sequence of characters
597 * currently contained in the string builder argument. The contents of the
598 * string builder are copied; subsequent modification of the string builder
599 * does not affect the newly created string.
601 * <p> This constructor is provided to ease migration to {@code
602 * StringBuilder}. Obtaining a string from a string builder via the {@code
603 * toString} method is likely to run faster and is generally preferred.
606 * A {@code StringBuilder}
610 public String(StringBuilder builder) {
611 this.r = builder.toString();
615 * Returns the length of this string.
616 * The length is equal to the number of <a href="Character.html#unicode">Unicode
617 * code units</a> in the string.
619 * @return the length of the sequence of characters represented by this
622 @JavaScriptBody(args = {}, body = "return this.toString().length;")
623 public int length() {
624 throw new UnsupportedOperationException();
628 * Returns <tt>true</tt> if, and only if, {@link #length()} is <tt>0</tt>.
630 * @return <tt>true</tt> if {@link #length()} is <tt>0</tt>, otherwise
635 @JavaScriptBody(args = {}, body="return this.toString().length === 0;")
636 public boolean isEmpty() {
637 return length() == 0;
641 * Returns the <code>char</code> value at the
642 * specified index. An index ranges from <code>0</code> to
643 * <code>length() - 1</code>. The first <code>char</code> value of the sequence
644 * is at index <code>0</code>, the next at index <code>1</code>,
645 * and so on, as for array indexing.
647 * <p>If the <code>char</code> value specified by the index is a
648 * <a href="Character.html#unicode">surrogate</a>, the surrogate
651 * @param index the index of the <code>char</code> value.
652 * @return the <code>char</code> value at the specified index of this string.
653 * The first <code>char</code> value is at index <code>0</code>.
654 * @exception IndexOutOfBoundsException if the <code>index</code>
655 * argument is negative or not less than the length of this
658 @JavaScriptBody(args = { "index" },
659 body = "return this.toString().charCodeAt(index);"
661 public char charAt(int index) {
662 throw new UnsupportedOperationException();
666 * Returns the character (Unicode code point) at the specified
667 * index. The index refers to <code>char</code> values
668 * (Unicode code units) and ranges from <code>0</code> to
669 * {@link #length()}<code> - 1</code>.
671 * <p> If the <code>char</code> value specified at the given index
672 * is in the high-surrogate range, the following index is less
673 * than the length of this <code>String</code>, and the
674 * <code>char</code> value at the following index is in the
675 * low-surrogate range, then the supplementary code point
676 * corresponding to this surrogate pair is returned. Otherwise,
677 * the <code>char</code> value at the given index is returned.
679 * @param index the index to the <code>char</code> values
680 * @return the code point value of the character at the
682 * @exception IndexOutOfBoundsException if the <code>index</code>
683 * argument is negative or not less than the length of this
687 public int codePointAt(int index) {
688 if ((index < 0) || (index >= length())) {
689 throw new StringIndexOutOfBoundsException(index);
691 return Character.codePointAtImpl(toCharArray(), offset() + index, offset() + length());
695 * Returns the character (Unicode code point) before the specified
696 * index. The index refers to <code>char</code> values
697 * (Unicode code units) and ranges from <code>1</code> to {@link
698 * CharSequence#length() length}.
700 * <p> If the <code>char</code> value at <code>(index - 1)</code>
701 * is in the low-surrogate range, <code>(index - 2)</code> is not
702 * negative, and the <code>char</code> value at <code>(index -
703 * 2)</code> is in the high-surrogate range, then the
704 * supplementary code point value of the surrogate pair is
705 * returned. If the <code>char</code> value at <code>index -
706 * 1</code> is an unpaired low-surrogate or a high-surrogate, the
707 * surrogate value is returned.
709 * @param index the index following the code point that should be returned
710 * @return the Unicode code point value before the given index.
711 * @exception IndexOutOfBoundsException if the <code>index</code>
712 * argument is less than 1 or greater than the length
716 public int codePointBefore(int index) {
718 if ((i < 0) || (i >= length())) {
719 throw new StringIndexOutOfBoundsException(index);
721 return Character.codePointBeforeImpl(toCharArray(), offset() + index, offset());
725 * Returns the number of Unicode code points in the specified text
726 * range of this <code>String</code>. The text range begins at the
727 * specified <code>beginIndex</code> and extends to the
728 * <code>char</code> at index <code>endIndex - 1</code>. Thus the
729 * length (in <code>char</code>s) of the text range is
730 * <code>endIndex-beginIndex</code>. Unpaired surrogates within
731 * the text range count as one code point each.
733 * @param beginIndex the index to the first <code>char</code> of
735 * @param endIndex the index after the last <code>char</code> of
737 * @return the number of Unicode code points in the specified text
739 * @exception IndexOutOfBoundsException if the
740 * <code>beginIndex</code> is negative, or <code>endIndex</code>
741 * is larger than the length of this <code>String</code>, or
742 * <code>beginIndex</code> is larger than <code>endIndex</code>.
745 public int codePointCount(int beginIndex, int endIndex) {
746 if (beginIndex < 0 || endIndex > length() || beginIndex > endIndex) {
747 throw new IndexOutOfBoundsException();
749 return Character.codePointCountImpl(toCharArray(), offset()+beginIndex, endIndex-beginIndex);
753 * Returns the index within this <code>String</code> that is
754 * offset from the given <code>index</code> by
755 * <code>codePointOffset</code> code points. Unpaired surrogates
756 * within the text range given by <code>index</code> and
757 * <code>codePointOffset</code> count as one code point each.
759 * @param index the index to be offset
760 * @param codePointOffset the offset in code points
761 * @return the index within this <code>String</code>
762 * @exception IndexOutOfBoundsException if <code>index</code>
763 * is negative or larger then the length of this
764 * <code>String</code>, or if <code>codePointOffset</code> is positive
765 * and the substring starting with <code>index</code> has fewer
766 * than <code>codePointOffset</code> code points,
767 * or if <code>codePointOffset</code> is negative and the substring
768 * before <code>index</code> has fewer than the absolute value
769 * of <code>codePointOffset</code> code points.
772 public int offsetByCodePoints(int index, int codePointOffset) {
773 if (index < 0 || index > length()) {
774 throw new IndexOutOfBoundsException();
776 return Character.offsetByCodePointsImpl(toCharArray(), offset(), length(),
777 offset()+index, codePointOffset) - offset();
781 * Copy characters from this string into dst starting at dstBegin.
782 * This method doesn't perform any range checking.
784 @JavaScriptBody(args = { "arr", "to" }, body =
785 "var s = this.toString();\n" +
786 "for (var i = 0; i < s.length; i++) {\n" +
787 " arr[to++] = s[i];\n" +
790 void getChars(char dst[], int dstBegin) {
791 System.arraycopy(toCharArray(), offset(), dst, dstBegin, length());
795 * Copies characters from this string into the destination character
798 * The first character to be copied is at index <code>srcBegin</code>;
799 * the last character to be copied is at index <code>srcEnd-1</code>
800 * (thus the total number of characters to be copied is
801 * <code>srcEnd-srcBegin</code>). The characters are copied into the
802 * subarray of <code>dst</code> starting at index <code>dstBegin</code>
803 * and ending at index:
804 * <p><blockquote><pre>
805 * dstbegin + (srcEnd-srcBegin) - 1
806 * </pre></blockquote>
808 * @param srcBegin index of the first character in the string
810 * @param srcEnd index after the last character in the string
812 * @param dst the destination array.
813 * @param dstBegin the start offset in the destination array.
814 * @exception IndexOutOfBoundsException If any of the following
816 * <ul><li><code>srcBegin</code> is negative.
817 * <li><code>srcBegin</code> is greater than <code>srcEnd</code>
818 * <li><code>srcEnd</code> is greater than the length of this
820 * <li><code>dstBegin</code> is negative
821 * <li><code>dstBegin+(srcEnd-srcBegin)</code> is larger than
822 * <code>dst.length</code></ul>
824 @JavaScriptBody(args = { "beg", "end", "arr", "dst" }, body=
825 "var s = this.toString();\n" +
826 "while (beg < end) {\n" +
827 " arr[dst++] = s.charCodeAt(beg++);\n" +
830 public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
832 throw new StringIndexOutOfBoundsException(srcBegin);
834 if (srcEnd > length()) {
835 throw new StringIndexOutOfBoundsException(srcEnd);
837 if (srcBegin > srcEnd) {
838 throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
840 System.arraycopy(toCharArray(), offset() + srcBegin, dst, dstBegin,
845 * Copies characters from this string into the destination byte array. Each
846 * byte receives the 8 low-order bits of the corresponding character. The
847 * eight high-order bits of each character are not copied and do not
848 * participate in the transfer in any way.
850 * <p> The first character to be copied is at index {@code srcBegin}; the
851 * last character to be copied is at index {@code srcEnd-1}. The total
852 * number of characters to be copied is {@code srcEnd-srcBegin}. The
853 * characters, converted to bytes, are copied into the subarray of {@code
854 * dst} starting at index {@code dstBegin} and ending at index:
857 * dstbegin + (srcEnd-srcBegin) - 1
858 * </pre></blockquote>
860 * @deprecated This method does not properly convert characters into
861 * bytes. As of JDK 1.1, the preferred way to do this is via the
862 * {@link #getBytes()} method, which uses the platform's default charset.
865 * Index of the first character in the string to copy
868 * Index after the last character in the string to copy
871 * The destination array
874 * The start offset in the destination array
876 * @throws IndexOutOfBoundsException
877 * If any of the following is true:
879 * <li> {@code srcBegin} is negative
880 * <li> {@code srcBegin} is greater than {@code srcEnd}
881 * <li> {@code srcEnd} is greater than the length of this String
882 * <li> {@code dstBegin} is negative
883 * <li> {@code dstBegin+(srcEnd-srcBegin)} is larger than {@code
888 public void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin) {
890 throw new StringIndexOutOfBoundsException(srcBegin);
892 if (srcEnd > length()) {
893 throw new StringIndexOutOfBoundsException(srcEnd);
895 if (srcBegin > srcEnd) {
896 throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
899 int n = offset() + srcEnd;
900 int i = offset() + srcBegin;
901 char[] val = toCharArray(); /* avoid getfield opcode */
904 dst[j++] = (byte)val[i++];
909 * Encodes this {@code String} into a sequence of bytes using the named
910 * charset, storing the result into a new byte array.
912 * <p> The behavior of this method when this string cannot be encoded in
913 * the given charset is unspecified. The {@link
914 * java.nio.charset.CharsetEncoder} class should be used when more control
915 * over the encoding process is required.
918 * The name of a supported {@linkplain java.nio.charset.Charset
921 * @return The resultant byte array
923 * @throws UnsupportedEncodingException
924 * If the named charset is not supported
928 // public byte[] getBytes(String charsetName)
929 // throws UnsupportedEncodingException
931 // if (charsetName == null) throw new NullPointerException();
932 // return StringCoding.encode(charsetName, value, offset, count);
936 * Encodes this {@code String} into a sequence of bytes using the given
937 * {@linkplain java.nio.charset.Charset charset}, storing the result into a
940 * <p> This method always replaces malformed-input and unmappable-character
941 * sequences with this charset's default replacement byte array. The
942 * {@link java.nio.charset.CharsetEncoder} class should be used when more
943 * control over the encoding process is required.
946 * The {@linkplain java.nio.charset.Charset} to be used to encode
949 * @return The resultant byte array
953 /* don't want dep on Charset
954 public byte[] getBytes(Charset charset) {
955 if (charset == null) throw new NullPointerException();
956 return StringCoding.encode(charset, value, offset, count);
961 * Encodes this {@code String} into a sequence of bytes using the
962 * platform's default charset, storing the result into a new byte array.
964 * <p> The behavior of this method when this string cannot be encoded in
965 * the default charset is unspecified. The {@link
966 * java.nio.charset.CharsetEncoder} class should be used when more control
967 * over the encoding process is required.
969 * @return The resultant byte array
973 public byte[] getBytes() {
975 byte[] arr = new byte[len];
976 for (int i = 0, j = 0; j < len; j++) {
977 final int v = charAt(j);
983 arr = System.expandArray(arr, i + 1);
984 arr[i++] = (byte) (0xC0 | (v >> 6));
985 arr[i++] = (byte) (0x80 | (0x3F & v));
988 arr = System.expandArray(arr, i + 2);
989 arr[i++] = (byte) (0xE0 | (v >> 12));
990 arr[i++] = (byte) (0x80 | ((v >> 6) & 0x7F));
991 arr[i++] = (byte) (0x80 | (0x3F & v));
997 * Compares this string to the specified object. The result is {@code
998 * true} if and only if the argument is not {@code null} and is a {@code
999 * String} object that represents the same sequence of characters as this
1003 * The object to compare this {@code String} against
1005 * @return {@code true} if the given object represents a {@code String}
1006 * equivalent to this string, {@code false} otherwise
1008 * @see #compareTo(String)
1009 * @see #equalsIgnoreCase(String)
1011 @JavaScriptBody(args = { "obj" }, body =
1012 "return obj != null && obj.$instOf_java_lang_String && "
1013 + "this.toString() === obj.toString();"
1015 public boolean equals(Object anObject) {
1016 if (this == anObject) {
1019 if (anObject instanceof String) {
1020 String anotherString = (String)anObject;
1022 if (n == anotherString.length()) {
1023 char v1[] = toCharArray();
1024 char v2[] = anotherString.toCharArray();
1026 int j = anotherString.offset();
1028 if (v1[i++] != v2[j++])
1038 * Compares this string to the specified {@code StringBuffer}. The result
1039 * is {@code true} if and only if this {@code String} represents the same
1040 * sequence of characters as the specified {@code StringBuffer}.
1043 * The {@code StringBuffer} to compare this {@code String} against
1045 * @return {@code true} if this {@code String} represents the same
1046 * sequence of characters as the specified {@code StringBuffer},
1047 * {@code false} otherwise
1051 public boolean contentEquals(StringBuffer sb) {
1053 return contentEquals((CharSequence)sb);
1058 * Compares this string to the specified {@code CharSequence}. The result
1059 * is {@code true} if and only if this {@code String} represents the same
1060 * sequence of char values as the specified sequence.
1063 * The sequence to compare this {@code String} against
1065 * @return {@code true} if this {@code String} represents the same
1066 * sequence of char values as the specified sequence, {@code
1071 public boolean contentEquals(CharSequence cs) {
1072 if (length() != cs.length())
1074 // Argument is a StringBuffer, StringBuilder
1075 if (cs instanceof AbstractStringBuilder) {
1076 char v1[] = toCharArray();
1077 char v2[] = ((AbstractStringBuilder)cs).getValue();
1082 if (v1[i++] != v2[j++])
1087 // Argument is a String
1088 if (cs.equals(this))
1090 // Argument is a generic CharSequence
1091 char v1[] = toCharArray();
1096 if (v1[i++] != cs.charAt(j++))
1103 * Compares this {@code String} to another {@code String}, ignoring case
1104 * considerations. Two strings are considered equal ignoring case if they
1105 * are of the same length and corresponding characters in the two strings
1106 * are equal ignoring case.
1108 * <p> Two characters {@code c1} and {@code c2} are considered the same
1109 * ignoring case if at least one of the following is true:
1111 * <li> The two characters are the same (as compared by the
1112 * {@code ==} operator)
1113 * <li> Applying the method {@link
1114 * java.lang.Character#toUpperCase(char)} to each character
1115 * produces the same result
1116 * <li> Applying the method {@link
1117 * java.lang.Character#toLowerCase(char)} to each character
1118 * produces the same result
1121 * @param anotherString
1122 * The {@code String} to compare this {@code String} against
1124 * @return {@code true} if the argument is not {@code null} and it
1125 * represents an equivalent {@code String} ignoring case; {@code
1128 * @see #equals(Object)
1130 public boolean equalsIgnoreCase(String anotherString) {
1131 return (this == anotherString) ? true :
1132 (anotherString != null) && (anotherString.length() == length()) &&
1133 regionMatches(true, 0, anotherString, 0, length());
1137 * Compares two strings lexicographically.
1138 * The comparison is based on the Unicode value of each character in
1139 * the strings. The character sequence represented by this
1140 * <code>String</code> object is compared lexicographically to the
1141 * character sequence represented by the argument string. The result is
1142 * a negative integer if this <code>String</code> object
1143 * lexicographically precedes the argument string. The result is a
1144 * positive integer if this <code>String</code> object lexicographically
1145 * follows the argument string. The result is zero if the strings
1146 * are equal; <code>compareTo</code> returns <code>0</code> exactly when
1147 * the {@link #equals(Object)} method would return <code>true</code>.
1149 * This is the definition of lexicographic ordering. If two strings are
1150 * different, then either they have different characters at some index
1151 * that is a valid index for both strings, or their lengths are different,
1152 * or both. If they have different characters at one or more index
1153 * positions, let <i>k</i> be the smallest such index; then the string
1154 * whose character at position <i>k</i> has the smaller value, as
1155 * determined by using the < operator, lexicographically precedes the
1156 * other string. In this case, <code>compareTo</code> returns the
1157 * difference of the two character values at position <code>k</code> in
1158 * the two string -- that is, the value:
1160 * this.charAt(k)-anotherString.charAt(k)
1161 * </pre></blockquote>
1162 * If there is no index position at which they differ, then the shorter
1163 * string lexicographically precedes the longer string. In this case,
1164 * <code>compareTo</code> returns the difference of the lengths of the
1165 * strings -- that is, the value:
1167 * this.length()-anotherString.length()
1168 * </pre></blockquote>
1170 * @param anotherString the <code>String</code> to be compared.
1171 * @return the value <code>0</code> if the argument string is equal to
1172 * this string; a value less than <code>0</code> if this string
1173 * is lexicographically less than the string argument; and a
1174 * value greater than <code>0</code> if this string is
1175 * lexicographically greater than the string argument.
1177 public int compareTo(String anotherString) {
1178 int len1 = length();
1179 int len2 = anotherString.length();
1180 int n = Math.min(len1, len2);
1181 char v1[] = toCharArray();
1182 char v2[] = anotherString.toCharArray();
1184 int j = anotherString.offset();
1210 * A Comparator that orders <code>String</code> objects as by
1211 * <code>compareToIgnoreCase</code>. This comparator is serializable.
1213 * Note that this Comparator does <em>not</em> take locale into account,
1214 * and will result in an unsatisfactory ordering for certain locales.
1215 * The java.text package provides <em>Collators</em> to allow
1216 * locale-sensitive ordering.
1218 * @see java.text.Collator#compare(String, String)
1221 public static final Comparator<String> CASE_INSENSITIVE_ORDER
1222 = new CaseInsensitiveComparator();
1224 private static int offset() {
1228 private static class CaseInsensitiveComparator
1229 implements Comparator<String>, java.io.Serializable {
1230 // use serialVersionUID from JDK 1.2.2 for interoperability
1231 private static final long serialVersionUID = 8575799808933029326L;
1233 public int compare(String s1, String s2) {
1234 int n1 = s1.length();
1235 int n2 = s2.length();
1236 int min = Math.min(n1, n2);
1237 for (int i = 0; i < min; i++) {
1238 char c1 = s1.charAt(i);
1239 char c2 = s2.charAt(i);
1241 c1 = Character.toUpperCase(c1);
1242 c2 = Character.toUpperCase(c2);
1244 c1 = Character.toLowerCase(c1);
1245 c2 = Character.toLowerCase(c2);
1247 // No overflow because of numeric promotion
1258 * Compares two strings lexicographically, ignoring case
1259 * differences. This method returns an integer whose sign is that of
1260 * calling <code>compareTo</code> with normalized versions of the strings
1261 * where case differences have been eliminated by calling
1262 * <code>Character.toLowerCase(Character.toUpperCase(character))</code> on
1265 * Note that this method does <em>not</em> take locale into account,
1266 * and will result in an unsatisfactory ordering for certain locales.
1267 * The java.text package provides <em>collators</em> to allow
1268 * locale-sensitive ordering.
1270 * @param str the <code>String</code> to be compared.
1271 * @return a negative integer, zero, or a positive integer as the
1272 * specified String is greater than, equal to, or less
1273 * than this String, ignoring case considerations.
1274 * @see java.text.Collator#compare(String, String)
1277 public int compareToIgnoreCase(String str) {
1278 return CASE_INSENSITIVE_ORDER.compare(this, str);
1282 * Tests if two string regions are equal.
1284 * A substring of this <tt>String</tt> object is compared to a substring
1285 * of the argument other. The result is true if these substrings
1286 * represent identical character sequences. The substring of this
1287 * <tt>String</tt> object to be compared begins at index <tt>toffset</tt>
1288 * and has length <tt>len</tt>. The substring of other to be compared
1289 * begins at index <tt>ooffset</tt> and has length <tt>len</tt>. The
1290 * result is <tt>false</tt> if and only if at least one of the following
1292 * <ul><li><tt>toffset</tt> is negative.
1293 * <li><tt>ooffset</tt> is negative.
1294 * <li><tt>toffset+len</tt> is greater than the length of this
1295 * <tt>String</tt> object.
1296 * <li><tt>ooffset+len</tt> is greater than the length of the other
1298 * <li>There is some nonnegative integer <i>k</i> less than <tt>len</tt>
1300 * <tt>this.charAt(toffset+<i>k</i>) != other.charAt(ooffset+<i>k</i>)</tt>
1303 * @param toffset the starting offset of the subregion in this string.
1304 * @param other the string argument.
1305 * @param ooffset the starting offset of the subregion in the string
1307 * @param len the number of characters to compare.
1308 * @return <code>true</code> if the specified subregion of this string
1309 * exactly matches the specified subregion of the string argument;
1310 * <code>false</code> otherwise.
1312 public boolean regionMatches(int toffset, String other, int ooffset,
1314 char ta[] = toCharArray();
1315 int to = offset() + toffset;
1316 char pa[] = other.toCharArray();
1317 int po = other.offset() + ooffset;
1318 // Note: toffset, ooffset, or len might be near -1>>>1.
1319 if ((ooffset < 0) || (toffset < 0) || (toffset > (long)length() - len)
1320 || (ooffset > (long)other.length() - len)) {
1324 if (ta[to++] != pa[po++]) {
1332 * Tests if two string regions are equal.
1334 * A substring of this <tt>String</tt> object is compared to a substring
1335 * of the argument <tt>other</tt>. The result is <tt>true</tt> if these
1336 * substrings represent character sequences that are the same, ignoring
1337 * case if and only if <tt>ignoreCase</tt> is true. The substring of
1338 * this <tt>String</tt> object to be compared begins at index
1339 * <tt>toffset</tt> and has length <tt>len</tt>. The substring of
1340 * <tt>other</tt> to be compared begins at index <tt>ooffset</tt> and
1341 * has length <tt>len</tt>. The result is <tt>false</tt> if and only if
1342 * at least one of the following is true:
1343 * <ul><li><tt>toffset</tt> is negative.
1344 * <li><tt>ooffset</tt> is negative.
1345 * <li><tt>toffset+len</tt> is greater than the length of this
1346 * <tt>String</tt> object.
1347 * <li><tt>ooffset+len</tt> is greater than the length of the other
1349 * <li><tt>ignoreCase</tt> is <tt>false</tt> and there is some nonnegative
1350 * integer <i>k</i> less than <tt>len</tt> such that:
1352 * this.charAt(toffset+k) != other.charAt(ooffset+k)
1353 * </pre></blockquote>
1354 * <li><tt>ignoreCase</tt> is <tt>true</tt> and there is some nonnegative
1355 * integer <i>k</i> less than <tt>len</tt> such that:
1357 * Character.toLowerCase(this.charAt(toffset+k)) !=
1358 Character.toLowerCase(other.charAt(ooffset+k))
1359 * </pre></blockquote>
1362 * Character.toUpperCase(this.charAt(toffset+k)) !=
1363 * Character.toUpperCase(other.charAt(ooffset+k))
1364 * </pre></blockquote>
1367 * @param ignoreCase if <code>true</code>, ignore case when comparing
1369 * @param toffset the starting offset of the subregion in this
1371 * @param other the string argument.
1372 * @param ooffset the starting offset of the subregion in the string
1374 * @param len the number of characters to compare.
1375 * @return <code>true</code> if the specified subregion of this string
1376 * matches the specified subregion of the string argument;
1377 * <code>false</code> otherwise. Whether the matching is exact
1378 * or case insensitive depends on the <code>ignoreCase</code>
1381 public boolean regionMatches(boolean ignoreCase, int toffset,
1382 String other, int ooffset, int len) {
1383 char ta[] = toCharArray();
1384 int to = offset() + toffset;
1385 char pa[] = other.toCharArray();
1386 int po = other.offset() + ooffset;
1387 // Note: toffset, ooffset, or len might be near -1>>>1.
1388 if ((ooffset < 0) || (toffset < 0) || (toffset > (long)length() - len) ||
1389 (ooffset > (long)other.length() - len)) {
1399 // If characters don't match but case may be ignored,
1400 // try converting both characters to uppercase.
1401 // If the results match, then the comparison scan should
1403 char u1 = Character.toUpperCase(c1);
1404 char u2 = Character.toUpperCase(c2);
1408 // Unfortunately, conversion to uppercase does not work properly
1409 // for the Georgian alphabet, which has strange rules about case
1410 // conversion. So we need to make one last check before
1412 if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) {
1422 * Tests if the substring of this string beginning at the
1423 * specified index starts with the specified prefix.
1425 * @param prefix the prefix.
1426 * @param toffset where to begin looking in this string.
1427 * @return <code>true</code> if the character sequence represented by the
1428 * argument is a prefix of the substring of this object starting
1429 * at index <code>toffset</code>; <code>false</code> otherwise.
1430 * The result is <code>false</code> if <code>toffset</code> is
1431 * negative or greater than the length of this
1432 * <code>String</code> object; otherwise the result is the same
1433 * as the result of the expression
1435 * this.substring(toffset).startsWith(prefix)
1438 @JavaScriptBody(args = { "find", "from" }, body=
1439 "find = find.toString();\n" +
1440 "return this.toString().substring(from, from + find.length) === find;\n"
1442 public boolean startsWith(String prefix, int toffset) {
1443 char ta[] = toCharArray();
1444 int to = offset() + toffset;
1445 char pa[] = prefix.toCharArray();
1446 int po = prefix.offset();
1447 int pc = prefix.length();
1448 // Note: toffset might be near -1>>>1.
1449 if ((toffset < 0) || (toffset > length() - pc)) {
1453 if (ta[to++] != pa[po++]) {
1461 * Tests if this string starts with the specified prefix.
1463 * @param prefix the prefix.
1464 * @return <code>true</code> if the character sequence represented by the
1465 * argument is a prefix of the character sequence represented by
1466 * this string; <code>false</code> otherwise.
1467 * Note also that <code>true</code> will be returned if the
1468 * argument is an empty string or is equal to this
1469 * <code>String</code> object as determined by the
1470 * {@link #equals(Object)} method.
1473 public boolean startsWith(String prefix) {
1474 return startsWith(prefix, 0);
1478 * Tests if this string ends with the specified suffix.
1480 * @param suffix the suffix.
1481 * @return <code>true</code> if the character sequence represented by the
1482 * argument is a suffix of the character sequence represented by
1483 * this object; <code>false</code> otherwise. Note that the
1484 * result will be <code>true</code> if the argument is the
1485 * empty string or is equal to this <code>String</code> object
1486 * as determined by the {@link #equals(Object)} method.
1488 public boolean endsWith(String suffix) {
1489 return startsWith(suffix, length() - suffix.length());
1493 * Returns a hash code for this string. The hash code for a
1494 * <code>String</code> object is computed as
1496 * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
1497 * </pre></blockquote>
1498 * using <code>int</code> arithmetic, where <code>s[i]</code> is the
1499 * <i>i</i>th character of the string, <code>n</code> is the length of
1500 * the string, and <code>^</code> indicates exponentiation.
1501 * (The hash value of the empty string is zero.)
1503 * @return a hash code value for this object.
1505 public int hashCode() {
1506 return super.hashCode();
1508 int computeHashCode() {
1510 if (h == 0 && length() > 0) {
1514 for (int i = 0; i < len; i++) {
1515 h = 31*h + charAt(off++);
1522 * Returns the index within this string of the first occurrence of
1523 * the specified character. If a character with value
1524 * <code>ch</code> occurs in the character sequence represented by
1525 * this <code>String</code> object, then the index (in Unicode
1526 * code units) of the first such occurrence is returned. For
1527 * values of <code>ch</code> in the range from 0 to 0xFFFF
1528 * (inclusive), this is the smallest value <i>k</i> such that:
1530 * this.charAt(<i>k</i>) == ch
1531 * </pre></blockquote>
1532 * is true. For other values of <code>ch</code>, it is the
1533 * smallest value <i>k</i> such that:
1535 * this.codePointAt(<i>k</i>) == ch
1536 * </pre></blockquote>
1537 * is true. In either case, if no such character occurs in this
1538 * string, then <code>-1</code> is returned.
1540 * @param ch a character (Unicode code point).
1541 * @return the index of the first occurrence of the character in the
1542 * character sequence represented by this object, or
1543 * <code>-1</code> if the character does not occur.
1545 public int indexOf(int ch) {
1546 return indexOf(ch, 0);
1550 * Returns the index within this string of the first occurrence of the
1551 * specified character, starting the search at the specified index.
1553 * If a character with value <code>ch</code> occurs in the
1554 * character sequence represented by this <code>String</code>
1555 * object at an index no smaller than <code>fromIndex</code>, then
1556 * the index of the first such occurrence is returned. For values
1557 * of <code>ch</code> in the range from 0 to 0xFFFF (inclusive),
1558 * this is the smallest value <i>k</i> such that:
1560 * (this.charAt(<i>k</i>) == ch) && (<i>k</i> >= fromIndex)
1561 * </pre></blockquote>
1562 * is true. For other values of <code>ch</code>, it is the
1563 * smallest value <i>k</i> such that:
1565 * (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> >= fromIndex)
1566 * </pre></blockquote>
1567 * is true. In either case, if no such character occurs in this
1568 * string at or after position <code>fromIndex</code>, then
1569 * <code>-1</code> is returned.
1572 * There is no restriction on the value of <code>fromIndex</code>. If it
1573 * is negative, it has the same effect as if it were zero: this entire
1574 * string may be searched. If it is greater than the length of this
1575 * string, it has the same effect as if it were equal to the length of
1576 * this string: <code>-1</code> is returned.
1578 * <p>All indices are specified in <code>char</code> values
1579 * (Unicode code units).
1581 * @param ch a character (Unicode code point).
1582 * @param fromIndex the index to start the search from.
1583 * @return the index of the first occurrence of the character in the
1584 * character sequence represented by this object that is greater
1585 * than or equal to <code>fromIndex</code>, or <code>-1</code>
1586 * if the character does not occur.
1588 @JavaScriptBody(args = { "ch", "from" }, body =
1589 "if (typeof ch === 'number') ch = String.fromCharCode(ch);\n" +
1590 "return this.toString().indexOf(ch, from);\n"
1592 public int indexOf(int ch, int fromIndex) {
1593 if (fromIndex < 0) {
1595 } else if (fromIndex >= length()) {
1596 // Note: fromIndex might be near -1>>>1.
1600 if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
1601 // handle most cases here (ch is a BMP code point or a
1602 // negative value (invalid code point))
1603 final char[] value = this.toCharArray();
1604 final int offset = this.offset();
1605 final int max = offset + length();
1606 for (int i = offset + fromIndex; i < max ; i++) {
1607 if (value[i] == ch) {
1613 return indexOfSupplementary(ch, fromIndex);
1618 * Handles (rare) calls of indexOf with a supplementary character.
1620 private int indexOfSupplementary(int ch, int fromIndex) {
1621 if (Character.isValidCodePoint(ch)) {
1622 final char[] value = this.toCharArray();
1623 final int offset = this.offset();
1624 final char hi = Character.highSurrogate(ch);
1625 final char lo = Character.lowSurrogate(ch);
1626 final int max = offset + length() - 1;
1627 for (int i = offset + fromIndex; i < max; i++) {
1628 if (value[i] == hi && value[i+1] == lo) {
1637 * Returns the index within this string of the last occurrence of
1638 * the specified character. For values of <code>ch</code> in the
1639 * range from 0 to 0xFFFF (inclusive), the index (in Unicode code
1640 * units) returned is the largest value <i>k</i> such that:
1642 * this.charAt(<i>k</i>) == ch
1643 * </pre></blockquote>
1644 * is true. For other values of <code>ch</code>, it is the
1645 * largest value <i>k</i> such that:
1647 * this.codePointAt(<i>k</i>) == ch
1648 * </pre></blockquote>
1649 * is true. In either case, if no such character occurs in this
1650 * string, then <code>-1</code> is returned. The
1651 * <code>String</code> is searched backwards starting at the last
1654 * @param ch a character (Unicode code point).
1655 * @return the index of the last occurrence of the character in the
1656 * character sequence represented by this object, or
1657 * <code>-1</code> if the character does not occur.
1659 public int lastIndexOf(int ch) {
1660 return lastIndexOf(ch, length() - 1);
1664 * Returns the index within this string of the last occurrence of
1665 * the specified character, searching backward starting at the
1666 * specified index. For values of <code>ch</code> in the range
1667 * from 0 to 0xFFFF (inclusive), the index returned is the largest
1668 * value <i>k</i> such that:
1670 * (this.charAt(<i>k</i>) == ch) && (<i>k</i> <= fromIndex)
1671 * </pre></blockquote>
1672 * is true. For other values of <code>ch</code>, it is the
1673 * largest value <i>k</i> such that:
1675 * (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> <= fromIndex)
1676 * </pre></blockquote>
1677 * is true. In either case, if no such character occurs in this
1678 * string at or before position <code>fromIndex</code>, then
1679 * <code>-1</code> is returned.
1681 * <p>All indices are specified in <code>char</code> values
1682 * (Unicode code units).
1684 * @param ch a character (Unicode code point).
1685 * @param fromIndex the index to start the search from. There is no
1686 * restriction on the value of <code>fromIndex</code>. If it is
1687 * greater than or equal to the length of this string, it has
1688 * the same effect as if it were equal to one less than the
1689 * length of this string: this entire string may be searched.
1690 * If it is negative, it has the same effect as if it were -1:
1692 * @return the index of the last occurrence of the character in the
1693 * character sequence represented by this object that is less
1694 * than or equal to <code>fromIndex</code>, or <code>-1</code>
1695 * if the character does not occur before that point.
1697 @JavaScriptBody(args = { "ch", "from" }, body =
1698 "if (typeof ch === 'number') ch = String.fromCharCode(ch);\n" +
1699 "return this.toString().lastIndexOf(ch, from);"
1701 public int lastIndexOf(int ch, int fromIndex) {
1702 if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
1703 // handle most cases here (ch is a BMP code point or a
1704 // negative value (invalid code point))
1705 final char[] value = this.toCharArray();
1706 final int offset = this.offset();
1707 int i = offset + Math.min(fromIndex, length() - 1);
1708 for (; i >= offset ; i--) {
1709 if (value[i] == ch) {
1715 return lastIndexOfSupplementary(ch, fromIndex);
1720 * Handles (rare) calls of lastIndexOf with a supplementary character.
1722 private int lastIndexOfSupplementary(int ch, int fromIndex) {
1723 if (Character.isValidCodePoint(ch)) {
1724 final char[] value = this.toCharArray();
1725 final int offset = this.offset();
1726 char hi = Character.highSurrogate(ch);
1727 char lo = Character.lowSurrogate(ch);
1728 int i = offset + Math.min(fromIndex, length() - 2);
1729 for (; i >= offset; i--) {
1730 if (value[i] == hi && value[i+1] == lo) {
1739 * Returns the index within this string of the first occurrence of the
1740 * specified substring.
1742 * <p>The returned index is the smallest value <i>k</i> for which:
1744 * this.startsWith(str, <i>k</i>)
1745 * </pre></blockquote>
1746 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1748 * @param str the substring to search for.
1749 * @return the index of the first occurrence of the specified substring,
1750 * or {@code -1} if there is no such occurrence.
1752 public int indexOf(String str) {
1753 return indexOf(str, 0);
1757 * Returns the index within this string of the first occurrence of the
1758 * specified substring, starting at the specified index.
1760 * <p>The returned index is the smallest value <i>k</i> for which:
1762 * <i>k</i> >= fromIndex && this.startsWith(str, <i>k</i>)
1763 * </pre></blockquote>
1764 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1766 * @param str the substring to search for.
1767 * @param fromIndex the index from which to start the search.
1768 * @return the index of the first occurrence of the specified substring,
1769 * starting at the specified index,
1770 * or {@code -1} if there is no such occurrence.
1772 @JavaScriptBody(args = { "str", "fromIndex" }, body =
1773 "return this.toString().indexOf(str.toString(), fromIndex);"
1775 public native int indexOf(String str, int fromIndex);
1778 * Returns the index within this string of the last occurrence of the
1779 * specified substring. The last occurrence of the empty string ""
1780 * is considered to occur at the index value {@code this.length()}.
1782 * <p>The returned index is the largest value <i>k</i> for which:
1784 * this.startsWith(str, <i>k</i>)
1785 * </pre></blockquote>
1786 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1788 * @param str the substring to search for.
1789 * @return the index of the last occurrence of the specified substring,
1790 * or {@code -1} if there is no such occurrence.
1792 public int lastIndexOf(String str) {
1793 return lastIndexOf(str, length());
1797 * Returns the index within this string of the last occurrence of the
1798 * specified substring, searching backward starting at the specified index.
1800 * <p>The returned index is the largest value <i>k</i> for which:
1802 * <i>k</i> <= fromIndex && this.startsWith(str, <i>k</i>)
1803 * </pre></blockquote>
1804 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1806 * @param str the substring to search for.
1807 * @param fromIndex the index to start the search from.
1808 * @return the index of the last occurrence of the specified substring,
1809 * searching backward from the specified index,
1810 * or {@code -1} if there is no such occurrence.
1812 @JavaScriptBody(args = { "s", "from" }, body =
1813 "return this.toString().lastIndexOf(s.toString(), from);"
1815 public int lastIndexOf(String str, int fromIndex) {
1816 return lastIndexOf(toCharArray(), offset(), length(), str.toCharArray(), str.offset(), str.length(), fromIndex);
1820 * Code shared by String and StringBuffer to do searches. The
1821 * source is the character array being searched, and the target
1822 * is the string being searched for.
1824 * @param source the characters being searched.
1825 * @param sourceOffset offset of the source string.
1826 * @param sourceCount count of the source string.
1827 * @param target the characters being searched for.
1828 * @param targetOffset offset of the target string.
1829 * @param targetCount count of the target string.
1830 * @param fromIndex the index to begin searching from.
1832 static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
1833 char[] target, int targetOffset, int targetCount,
1836 * Check arguments; return immediately where possible. For
1837 * consistency, don't check for null str.
1839 int rightIndex = sourceCount - targetCount;
1840 if (fromIndex < 0) {
1843 if (fromIndex > rightIndex) {
1844 fromIndex = rightIndex;
1846 /* Empty string always matches. */
1847 if (targetCount == 0) {
1851 int strLastIndex = targetOffset + targetCount - 1;
1852 char strLastChar = target[strLastIndex];
1853 int min = sourceOffset + targetCount - 1;
1854 int i = min + fromIndex;
1856 startSearchForLastChar:
1858 while (i >= min && source[i] != strLastChar) {
1865 int start = j - (targetCount - 1);
1866 int k = strLastIndex - 1;
1869 if (source[j--] != target[k--]) {
1871 continue startSearchForLastChar;
1874 return start - sourceOffset + 1;
1879 * Returns a new string that is a substring of this string. The
1880 * substring begins with the character at the specified index and
1881 * extends to the end of this string. <p>
1884 * "unhappy".substring(2) returns "happy"
1885 * "Harbison".substring(3) returns "bison"
1886 * "emptiness".substring(9) returns "" (an empty string)
1887 * </pre></blockquote>
1889 * @param beginIndex the beginning index, inclusive.
1890 * @return the specified substring.
1891 * @exception IndexOutOfBoundsException if
1892 * <code>beginIndex</code> is negative or larger than the
1893 * length of this <code>String</code> object.
1895 public String substring(int beginIndex) {
1896 return substring(beginIndex, length());
1900 * Returns a new string that is a substring of this string. The
1901 * substring begins at the specified <code>beginIndex</code> and
1902 * extends to the character at index <code>endIndex - 1</code>.
1903 * Thus the length of the substring is <code>endIndex-beginIndex</code>.
1907 * "hamburger".substring(4, 8) returns "urge"
1908 * "smiles".substring(1, 5) returns "mile"
1909 * </pre></blockquote>
1911 * @param beginIndex the beginning index, inclusive.
1912 * @param endIndex the ending index, exclusive.
1913 * @return the specified substring.
1914 * @exception IndexOutOfBoundsException if the
1915 * <code>beginIndex</code> is negative, or
1916 * <code>endIndex</code> is larger than the length of
1917 * this <code>String</code> object, or
1918 * <code>beginIndex</code> is larger than
1919 * <code>endIndex</code>.
1921 @JavaScriptBody(args = { "beginIndex", "endIndex" }, body =
1922 "return this.toString().substring(beginIndex, endIndex);"
1924 public String substring(int beginIndex, int endIndex) {
1925 if (beginIndex < 0) {
1926 throw new StringIndexOutOfBoundsException(beginIndex);
1928 if (endIndex > length()) {
1929 throw new StringIndexOutOfBoundsException(endIndex);
1931 if (beginIndex > endIndex) {
1932 throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
1934 return ((beginIndex == 0) && (endIndex == length())) ? this :
1935 new String(toCharArray(), offset() + beginIndex, endIndex - beginIndex);
1939 * Returns a new character sequence that is a subsequence of this sequence.
1941 * <p> An invocation of this method of the form
1944 * str.subSequence(begin, end)</pre></blockquote>
1946 * behaves in exactly the same way as the invocation
1949 * str.substring(begin, end)</pre></blockquote>
1951 * This method is defined so that the <tt>String</tt> class can implement
1952 * the {@link CharSequence} interface. </p>
1954 * @param beginIndex the begin index, inclusive.
1955 * @param endIndex the end index, exclusive.
1956 * @return the specified subsequence.
1958 * @throws IndexOutOfBoundsException
1959 * if <tt>beginIndex</tt> or <tt>endIndex</tt> are negative,
1960 * if <tt>endIndex</tt> is greater than <tt>length()</tt>,
1961 * or if <tt>beginIndex</tt> is greater than <tt>startIndex</tt>
1966 public CharSequence subSequence(int beginIndex, int endIndex) {
1967 return this.substring(beginIndex, endIndex);
1971 * Concatenates the specified string to the end of this string.
1973 * If the length of the argument string is <code>0</code>, then this
1974 * <code>String</code> object is returned. Otherwise, a new
1975 * <code>String</code> object is created, representing a character
1976 * sequence that is the concatenation of the character sequence
1977 * represented by this <code>String</code> object and the character
1978 * sequence represented by the argument string.<p>
1981 * "cares".concat("s") returns "caress"
1982 * "to".concat("get").concat("her") returns "together"
1983 * </pre></blockquote>
1985 * @param str the <code>String</code> that is concatenated to the end
1986 * of this <code>String</code>.
1987 * @return a string that represents the concatenation of this object's
1988 * characters followed by the string argument's characters.
1990 public String concat(String str) {
1991 int otherLen = str.length();
1992 if (otherLen == 0) {
1995 char buf[] = new char[length() + otherLen];
1996 getChars(0, length(), buf, 0);
1997 str.getChars(0, otherLen, buf, length());
1998 return new String(buf, 0, length() + otherLen);
2002 * Returns a new string resulting from replacing all occurrences of
2003 * <code>oldChar</code> in this string with <code>newChar</code>.
2005 * If the character <code>oldChar</code> does not occur in the
2006 * character sequence represented by this <code>String</code> object,
2007 * then a reference to this <code>String</code> object is returned.
2008 * Otherwise, a new <code>String</code> object is created that
2009 * represents a character sequence identical to the character sequence
2010 * represented by this <code>String</code> object, except that every
2011 * occurrence of <code>oldChar</code> is replaced by an occurrence
2012 * of <code>newChar</code>.
2016 * "mesquite in your cellar".replace('e', 'o')
2017 * returns "mosquito in your collar"
2018 * "the war of baronets".replace('r', 'y')
2019 * returns "the way of bayonets"
2020 * "sparring with a purple porpoise".replace('p', 't')
2021 * returns "starring with a turtle tortoise"
2022 * "JonL".replace('q', 'x') returns "JonL" (no change)
2023 * </pre></blockquote>
2025 * @param oldChar the old character.
2026 * @param newChar the new character.
2027 * @return a string derived from this string by replacing every
2028 * occurrence of <code>oldChar</code> with <code>newChar</code>.
2030 @JavaScriptBody(args = { "arg1", "arg2" }, body =
2031 "if (typeof arg1 === 'number') arg1 = String.fromCharCode(arg1);\n" +
2032 "if (typeof arg2 === 'number') arg2 = String.fromCharCode(arg2);\n" +
2033 "var s = this.toString();\n" +
2035 " var ret = s.replace(arg1, arg2);\n" +
2036 " if (ret === s) {\n" +
2042 public String replace(char oldChar, char newChar) {
2043 if (oldChar != newChar) {
2046 char[] val = toCharArray(); /* avoid getfield opcode */
2047 int off = offset(); /* avoid getfield opcode */
2050 if (val[off + i] == oldChar) {
2055 char buf[] = new char[len];
2056 for (int j = 0 ; j < i ; j++) {
2057 buf[j] = val[off+j];
2060 char c = val[off + i];
2061 buf[i] = (c == oldChar) ? newChar : c;
2064 return new String(buf, 0, len);
2071 * Tells whether or not this string matches the given <a
2072 * href="../util/regex/Pattern.html#sum">regular expression</a>.
2074 * <p> An invocation of this method of the form
2075 * <i>str</i><tt>.matches(</tt><i>regex</i><tt>)</tt> yields exactly the
2076 * same result as the expression
2078 * <blockquote><tt> {@link java.util.regex.Pattern}.{@link
2079 * java.util.regex.Pattern#matches(String,CharSequence)
2080 * matches}(</tt><i>regex</i><tt>,</tt> <i>str</i><tt>)</tt></blockquote>
2083 * the regular expression to which this string is to be matched
2085 * @return <tt>true</tt> if, and only if, this string matches the
2086 * given regular expression
2088 * @throws PatternSyntaxException
2089 * if the regular expression's syntax is invalid
2091 * @see java.util.regex.Pattern
2096 @JavaScriptBody(args = { "regex" }, body =
2097 "var self = this.toString();\n"
2098 + "var re = new RegExp(regex.toString());\n"
2099 + "var r = re.exec(self);\n"
2100 + "return r != null && r.length > 0 && self.length == r[0].length;"
2102 public boolean matches(String regex) {
2103 throw new UnsupportedOperationException();
2107 * Returns true if and only if this string contains the specified
2108 * sequence of char values.
2110 * @param s the sequence to search for
2111 * @return true if this string contains <code>s</code>, false otherwise
2112 * @throws NullPointerException if <code>s</code> is <code>null</code>
2115 public boolean contains(CharSequence s) {
2116 return indexOf(s.toString()) > -1;
2120 * Replaces the first substring of this string that matches the given <a
2121 * href="../util/regex/Pattern.html#sum">regular expression</a> with the
2122 * given replacement.
2124 * <p> An invocation of this method of the form
2125 * <i>str</i><tt>.replaceFirst(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt>
2126 * yields exactly the same result as the expression
2129 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2130 * compile}(</tt><i>regex</i><tt>).{@link
2131 * java.util.regex.Pattern#matcher(java.lang.CharSequence)
2132 * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceFirst
2133 * replaceFirst}(</tt><i>repl</i><tt>)</tt></blockquote>
2136 * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the
2137 * replacement string may cause the results to be different than if it were
2138 * being treated as a literal replacement string; see
2139 * {@link java.util.regex.Matcher#replaceFirst}.
2140 * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
2141 * meaning of these characters, if desired.
2144 * the regular expression to which this string is to be matched
2145 * @param replacement
2146 * the string to be substituted for the first match
2148 * @return The resulting <tt>String</tt>
2150 * @throws PatternSyntaxException
2151 * if the regular expression's syntax is invalid
2153 * @see java.util.regex.Pattern
2158 public String replaceFirst(String regex, String replacement) {
2159 throw new UnsupportedOperationException();
2163 * Replaces each substring of this string that matches the given <a
2164 * href="../util/regex/Pattern.html#sum">regular expression</a> with the
2165 * given replacement.
2167 * <p> An invocation of this method of the form
2168 * <i>str</i><tt>.replaceAll(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt>
2169 * yields exactly the same result as the expression
2172 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2173 * compile}(</tt><i>regex</i><tt>).{@link
2174 * java.util.regex.Pattern#matcher(java.lang.CharSequence)
2175 * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceAll
2176 * replaceAll}(</tt><i>repl</i><tt>)</tt></blockquote>
2179 * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the
2180 * replacement string may cause the results to be different than if it were
2181 * being treated as a literal replacement string; see
2182 * {@link java.util.regex.Matcher#replaceAll Matcher.replaceAll}.
2183 * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
2184 * meaning of these characters, if desired.
2187 * the regular expression to which this string is to be matched
2188 * @param replacement
2189 * the string to be substituted for each match
2191 * @return The resulting <tt>String</tt>
2193 * @throws PatternSyntaxException
2194 * if the regular expression's syntax is invalid
2196 * @see java.util.regex.Pattern
2201 public String replaceAll(String regex, String replacement) {
2202 throw new UnsupportedOperationException();
2206 * Replaces each substring of this string that matches the literal target
2207 * sequence with the specified literal replacement sequence. The
2208 * replacement proceeds from the beginning of the string to the end, for
2209 * example, replacing "aa" with "b" in the string "aaa" will result in
2210 * "ba" rather than "ab".
2212 * @param target The sequence of char values to be replaced
2213 * @param replacement The replacement sequence of char values
2214 * @return The resulting string
2215 * @throws NullPointerException if <code>target</code> or
2216 * <code>replacement</code> is <code>null</code>.
2219 public String replace(CharSequence target, CharSequence replacement) {
2220 throw new UnsupportedOperationException("This one should be supported, but without dep on rest of regexp");
2224 * Splits this string around matches of the given
2225 * <a href="../util/regex/Pattern.html#sum">regular expression</a>.
2227 * <p> The array returned by this method contains each substring of this
2228 * string that is terminated by another substring that matches the given
2229 * expression or is terminated by the end of the string. The substrings in
2230 * the array are in the order in which they occur in this string. If the
2231 * expression does not match any part of the input then the resulting array
2232 * has just one element, namely this string.
2234 * <p> The <tt>limit</tt> parameter controls the number of times the
2235 * pattern is applied and therefore affects the length of the resulting
2236 * array. If the limit <i>n</i> is greater than zero then the pattern
2237 * will be applied at most <i>n</i> - 1 times, the array's
2238 * length will be no greater than <i>n</i>, and the array's last entry
2239 * will contain all input beyond the last matched delimiter. If <i>n</i>
2240 * is non-positive then the pattern will be applied as many times as
2241 * possible and the array can have any length. If <i>n</i> is zero then
2242 * the pattern will be applied as many times as possible, the array can
2243 * have any length, and trailing empty strings will be discarded.
2245 * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the
2246 * following results with these parameters:
2248 * <blockquote><table cellpadding=1 cellspacing=0 summary="Split example showing regex, limit, and result">
2254 * <tr><td align=center>:</td>
2255 * <td align=center>2</td>
2256 * <td><tt>{ "boo", "and:foo" }</tt></td></tr>
2257 * <tr><td align=center>:</td>
2258 * <td align=center>5</td>
2259 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2260 * <tr><td align=center>:</td>
2261 * <td align=center>-2</td>
2262 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2263 * <tr><td align=center>o</td>
2264 * <td align=center>5</td>
2265 * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
2266 * <tr><td align=center>o</td>
2267 * <td align=center>-2</td>
2268 * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
2269 * <tr><td align=center>o</td>
2270 * <td align=center>0</td>
2271 * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
2272 * </table></blockquote>
2274 * <p> An invocation of this method of the form
2275 * <i>str.</i><tt>split(</tt><i>regex</i><tt>,</tt> <i>n</i><tt>)</tt>
2276 * yields the same result as the expression
2279 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2280 * compile}<tt>(</tt><i>regex</i><tt>)</tt>.{@link
2281 * java.util.regex.Pattern#split(java.lang.CharSequence,int)
2282 * split}<tt>(</tt><i>str</i><tt>,</tt> <i>n</i><tt>)</tt>
2287 * the delimiting regular expression
2290 * the result threshold, as described above
2292 * @return the array of strings computed by splitting this string
2293 * around matches of the given regular expression
2295 * @throws PatternSyntaxException
2296 * if the regular expression's syntax is invalid
2298 * @see java.util.regex.Pattern
2303 public String[] split(String regex, int limit) {
2304 throw new UnsupportedOperationException("Needs regexp");
2308 * Splits this string around matches of the given <a
2309 * href="../util/regex/Pattern.html#sum">regular expression</a>.
2311 * <p> This method works as if by invoking the two-argument {@link
2312 * #split(String, int) split} method with the given expression and a limit
2313 * argument of zero. Trailing empty strings are therefore not included in
2314 * the resulting array.
2316 * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the following
2317 * results with these expressions:
2319 * <blockquote><table cellpadding=1 cellspacing=0 summary="Split examples showing regex and result">
2324 * <tr><td align=center>:</td>
2325 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2326 * <tr><td align=center>o</td>
2327 * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
2328 * </table></blockquote>
2332 * the delimiting regular expression
2334 * @return the array of strings computed by splitting this string
2335 * around matches of the given regular expression
2337 * @throws PatternSyntaxException
2338 * if the regular expression's syntax is invalid
2340 * @see java.util.regex.Pattern
2345 public String[] split(String regex) {
2346 return split(regex, 0);
2350 * Converts all of the characters in this <code>String</code> to lower
2351 * case using the rules of the given <code>Locale</code>. Case mapping is based
2352 * on the Unicode Standard version specified by the {@link java.lang.Character Character}
2353 * class. Since case mappings are not always 1:1 char mappings, the resulting
2354 * <code>String</code> may be a different length than the original <code>String</code>.
2356 * Examples of lowercase mappings are in the following table:
2357 * <table border="1" summary="Lowercase mapping examples showing language code of locale, upper case, lower case, and description">
2359 * <th>Language Code of Locale</th>
2360 * <th>Upper Case</th>
2361 * <th>Lower Case</th>
2362 * <th>Description</th>
2365 * <td>tr (Turkish)</td>
2366 * <td>\u0130</td>
2367 * <td>\u0069</td>
2368 * <td>capital letter I with dot above -> small letter i</td>
2371 * <td>tr (Turkish)</td>
2372 * <td>\u0049</td>
2373 * <td>\u0131</td>
2374 * <td>capital letter I -> small letter dotless i </td>
2378 * <td>French Fries</td>
2379 * <td>french fries</td>
2380 * <td>lowercased all chars in String</td>
2384 * <td><img src="doc-files/capiota.gif" alt="capiota"><img src="doc-files/capchi.gif" alt="capchi">
2385 * <img src="doc-files/captheta.gif" alt="captheta"><img src="doc-files/capupsil.gif" alt="capupsil">
2386 * <img src="doc-files/capsigma.gif" alt="capsigma"></td>
2387 * <td><img src="doc-files/iota.gif" alt="iota"><img src="doc-files/chi.gif" alt="chi">
2388 * <img src="doc-files/theta.gif" alt="theta"><img src="doc-files/upsilon.gif" alt="upsilon">
2389 * <img src="doc-files/sigma1.gif" alt="sigma"></td>
2390 * <td>lowercased all chars in String</td>
2394 * @param locale use the case transformation rules for this locale
2395 * @return the <code>String</code>, converted to lowercase.
2396 * @see java.lang.String#toLowerCase()
2397 * @see java.lang.String#toUpperCase()
2398 * @see java.lang.String#toUpperCase(Locale)
2401 // public String toLowerCase(Locale locale) {
2402 // if (locale == null) {
2403 // throw new NullPointerException();
2408 // /* Now check if there are any characters that need to be changed. */
2410 // for (firstUpper = 0 ; firstUpper < count; ) {
2411 // char c = value[offset+firstUpper];
2412 // if ((c >= Character.MIN_HIGH_SURROGATE) &&
2413 // (c <= Character.MAX_HIGH_SURROGATE)) {
2414 // int supplChar = codePointAt(firstUpper);
2415 // if (supplChar != Character.toLowerCase(supplChar)) {
2418 // firstUpper += Character.charCount(supplChar);
2420 // if (c != Character.toLowerCase(c)) {
2429 // char[] result = new char[count];
2430 // int resultOffset = 0; /* result may grow, so i+resultOffset
2431 // * is the write location in result */
2433 // /* Just copy the first few lowerCase characters. */
2434 // System.arraycopy(value, offset, result, 0, firstUpper);
2436 // String lang = locale.getLanguage();
2437 // boolean localeDependent =
2438 // (lang == "tr" || lang == "az" || lang == "lt");
2439 // char[] lowerCharArray;
2443 // for (int i = firstUpper; i < count; i += srcCount) {
2444 // srcChar = (int)value[offset+i];
2445 // if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
2446 // (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
2447 // srcChar = codePointAt(i);
2448 // srcCount = Character.charCount(srcChar);
2452 // if (localeDependent || srcChar == '\u03A3') { // GREEK CAPITAL LETTER SIGMA
2453 // lowerChar = ConditionalSpecialCasing.toLowerCaseEx(this, i, locale);
2454 // } else if (srcChar == '\u0130') { // LATIN CAPITAL LETTER I DOT
2455 // lowerChar = Character.ERROR;
2457 // lowerChar = Character.toLowerCase(srcChar);
2459 // if ((lowerChar == Character.ERROR) ||
2460 // (lowerChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
2461 // if (lowerChar == Character.ERROR) {
2462 // if (!localeDependent && srcChar == '\u0130') {
2464 // ConditionalSpecialCasing.toLowerCaseCharArray(this, i, Locale.ENGLISH);
2467 // ConditionalSpecialCasing.toLowerCaseCharArray(this, i, locale);
2469 // } else if (srcCount == 2) {
2470 // resultOffset += Character.toChars(lowerChar, result, i + resultOffset) - srcCount;
2473 // lowerCharArray = Character.toChars(lowerChar);
2476 // /* Grow result if needed */
2477 // int mapLen = lowerCharArray.length;
2478 // if (mapLen > srcCount) {
2479 // char[] result2 = new char[result.length + mapLen - srcCount];
2480 // System.arraycopy(result, 0, result2, 0,
2481 // i + resultOffset);
2482 // result = result2;
2484 // for (int x=0; x<mapLen; ++x) {
2485 // result[i+resultOffset+x] = lowerCharArray[x];
2487 // resultOffset += (mapLen - srcCount);
2489 // result[i+resultOffset] = (char)lowerChar;
2492 // return new String(0, count+resultOffset, result);
2496 * Converts all of the characters in this <code>String</code> to lower
2497 * case using the rules of the default locale. This is equivalent to calling
2498 * <code>toLowerCase(Locale.getDefault())</code>.
2500 * <b>Note:</b> This method is locale sensitive, and may produce unexpected
2501 * results if used for strings that are intended to be interpreted locale
2503 * Examples are programming language identifiers, protocol keys, and HTML
2505 * For instance, <code>"TITLE".toLowerCase()</code> in a Turkish locale
2506 * returns <code>"t\u005Cu0131tle"</code>, where '\u005Cu0131' is the
2507 * LATIN SMALL LETTER DOTLESS I character.
2508 * To obtain correct results for locale insensitive strings, use
2509 * <code>toLowerCase(Locale.ENGLISH)</code>.
2511 * @return the <code>String</code>, converted to lowercase.
2512 * @see java.lang.String#toLowerCase(Locale)
2514 @JavaScriptBody(args = {}, body = "return this.toLowerCase();")
2515 public String toLowerCase() {
2516 throw new UnsupportedOperationException("Should be supported but without connection to locale");
2520 * Converts all of the characters in this <code>String</code> to upper
2521 * case using the rules of the given <code>Locale</code>. Case mapping is based
2522 * on the Unicode Standard version specified by the {@link java.lang.Character Character}
2523 * class. Since case mappings are not always 1:1 char mappings, the resulting
2524 * <code>String</code> may be a different length than the original <code>String</code>.
2526 * Examples of locale-sensitive and 1:M case mappings are in the following table.
2528 * <table border="1" summary="Examples of locale-sensitive and 1:M case mappings. Shows Language code of locale, lower case, upper case, and description.">
2530 * <th>Language Code of Locale</th>
2531 * <th>Lower Case</th>
2532 * <th>Upper Case</th>
2533 * <th>Description</th>
2536 * <td>tr (Turkish)</td>
2537 * <td>\u0069</td>
2538 * <td>\u0130</td>
2539 * <td>small letter i -> capital letter I with dot above</td>
2542 * <td>tr (Turkish)</td>
2543 * <td>\u0131</td>
2544 * <td>\u0049</td>
2545 * <td>small letter dotless i -> capital letter I</td>
2549 * <td>\u00df</td>
2550 * <td>\u0053 \u0053</td>
2551 * <td>small letter sharp s -> two letters: SS</td>
2555 * <td>Fahrvergnügen</td>
2556 * <td>FAHRVERGNÜGEN</td>
2560 * @param locale use the case transformation rules for this locale
2561 * @return the <code>String</code>, converted to uppercase.
2562 * @see java.lang.String#toUpperCase()
2563 * @see java.lang.String#toLowerCase()
2564 * @see java.lang.String#toLowerCase(Locale)
2567 /* not for javascript
2568 public String toUpperCase(Locale locale) {
2569 if (locale == null) {
2570 throw new NullPointerException();
2575 // Now check if there are any characters that need to be changed.
2577 for (firstLower = 0 ; firstLower < count; ) {
2578 int c = (int)value[offset+firstLower];
2580 if ((c >= Character.MIN_HIGH_SURROGATE) &&
2581 (c <= Character.MAX_HIGH_SURROGATE)) {
2582 c = codePointAt(firstLower);
2583 srcCount = Character.charCount(c);
2587 int upperCaseChar = Character.toUpperCaseEx(c);
2588 if ((upperCaseChar == Character.ERROR) ||
2589 (c != upperCaseChar)) {
2592 firstLower += srcCount;
2597 char[] result = new char[count]; /* may grow *
2598 int resultOffset = 0; /* result may grow, so i+resultOffset
2599 * is the write location in result *
2601 /* Just copy the first few upperCase characters. *
2602 System.arraycopy(value, offset, result, 0, firstLower);
2604 String lang = locale.getLanguage();
2605 boolean localeDependent =
2606 (lang == "tr" || lang == "az" || lang == "lt");
2607 char[] upperCharArray;
2611 for (int i = firstLower; i < count; i += srcCount) {
2612 srcChar = (int)value[offset+i];
2613 if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
2614 (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
2615 srcChar = codePointAt(i);
2616 srcCount = Character.charCount(srcChar);
2620 if (localeDependent) {
2621 upperChar = ConditionalSpecialCasing.toUpperCaseEx(this, i, locale);
2623 upperChar = Character.toUpperCaseEx(srcChar);
2625 if ((upperChar == Character.ERROR) ||
2626 (upperChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
2627 if (upperChar == Character.ERROR) {
2628 if (localeDependent) {
2630 ConditionalSpecialCasing.toUpperCaseCharArray(this, i, locale);
2632 upperCharArray = Character.toUpperCaseCharArray(srcChar);
2634 } else if (srcCount == 2) {
2635 resultOffset += Character.toChars(upperChar, result, i + resultOffset) - srcCount;
2638 upperCharArray = Character.toChars(upperChar);
2641 /* Grow result if needed *
2642 int mapLen = upperCharArray.length;
2643 if (mapLen > srcCount) {
2644 char[] result2 = new char[result.length + mapLen - srcCount];
2645 System.arraycopy(result, 0, result2, 0,
2649 for (int x=0; x<mapLen; ++x) {
2650 result[i+resultOffset+x] = upperCharArray[x];
2652 resultOffset += (mapLen - srcCount);
2654 result[i+resultOffset] = (char)upperChar;
2657 return new String(0, count+resultOffset, result);
2662 * Converts all of the characters in this <code>String</code> to upper
2663 * case using the rules of the default locale. This method is equivalent to
2664 * <code>toUpperCase(Locale.getDefault())</code>.
2666 * <b>Note:</b> This method is locale sensitive, and may produce unexpected
2667 * results if used for strings that are intended to be interpreted locale
2669 * Examples are programming language identifiers, protocol keys, and HTML
2671 * For instance, <code>"title".toUpperCase()</code> in a Turkish locale
2672 * returns <code>"T\u005Cu0130TLE"</code>, where '\u005Cu0130' is the
2673 * LATIN CAPITAL LETTER I WITH DOT ABOVE character.
2674 * To obtain correct results for locale insensitive strings, use
2675 * <code>toUpperCase(Locale.ENGLISH)</code>.
2677 * @return the <code>String</code>, converted to uppercase.
2678 * @see java.lang.String#toUpperCase(Locale)
2680 @JavaScriptBody(args = {}, body = "return this.toUpperCase();")
2681 public String toUpperCase() {
2682 throw new UnsupportedOperationException();
2686 * Returns a copy of the string, with leading and trailing whitespace
2689 * If this <code>String</code> object represents an empty character
2690 * sequence, or the first and last characters of character sequence
2691 * represented by this <code>String</code> object both have codes
2692 * greater than <code>'\u0020'</code> (the space character), then a
2693 * reference to this <code>String</code> object is returned.
2695 * Otherwise, if there is no character with a code greater than
2696 * <code>'\u0020'</code> in the string, then a new
2697 * <code>String</code> object representing an empty string is created
2700 * Otherwise, let <i>k</i> be the index of the first character in the
2701 * string whose code is greater than <code>'\u0020'</code>, and let
2702 * <i>m</i> be the index of the last character in the string whose code
2703 * is greater than <code>'\u0020'</code>. A new <code>String</code>
2704 * object is created, representing the substring of this string that
2705 * begins with the character at index <i>k</i> and ends with the
2706 * character at index <i>m</i>-that is, the result of
2707 * <code>this.substring(<i>k</i>, <i>m</i>+1)</code>.
2709 * This method may be used to trim whitespace (as defined above) from
2710 * the beginning and end of a string.
2712 * @return A copy of this string with leading and trailing white
2713 * space removed, or this string if it has no leading or
2714 * trailing white space.
2716 public String trim() {
2719 int off = offset(); /* avoid getfield opcode */
2720 char[] val = toCharArray(); /* avoid getfield opcode */
2722 while ((st < len) && (val[off + st] <= ' ')) {
2725 while ((st < len) && (val[off + len - 1] <= ' ')) {
2728 return ((st > 0) || (len < length())) ? substring(st, len) : this;
2732 * This object (which is already a string!) is itself returned.
2734 * @return the string itself.
2736 @JavaScriptBody(args = {}, body = "return this.toString();")
2737 public String toString() {
2742 * Converts this string to a new character array.
2744 * @return a newly allocated character array whose length is the length
2745 * of this string and whose contents are initialized to contain
2746 * the character sequence represented by this string.
2748 public char[] toCharArray() {
2749 char result[] = new char[length()];
2750 getChars(0, length(), result, 0);
2755 * Returns a formatted string using the specified format string and
2758 * <p> The locale always used is the one returned by {@link
2759 * java.util.Locale#getDefault() Locale.getDefault()}.
2762 * A <a href="../util/Formatter.html#syntax">format string</a>
2765 * Arguments referenced by the format specifiers in the format
2766 * string. If there are more arguments than format specifiers, the
2767 * extra arguments are ignored. The number of arguments is
2768 * variable and may be zero. The maximum number of arguments is
2769 * limited by the maximum dimension of a Java array as defined by
2770 * <cite>The Java™ Virtual Machine Specification</cite>.
2771 * The behaviour on a
2772 * <tt>null</tt> argument depends on the <a
2773 * href="../util/Formatter.html#syntax">conversion</a>.
2775 * @throws IllegalFormatException
2776 * If a format string contains an illegal syntax, a format
2777 * specifier that is incompatible with the given arguments,
2778 * insufficient arguments given the format string, or other
2779 * illegal conditions. For specification of all possible
2780 * formatting errors, see the <a
2781 * href="../util/Formatter.html#detail">Details</a> section of the
2782 * formatter class specification.
2784 * @throws NullPointerException
2785 * If the <tt>format</tt> is <tt>null</tt>
2787 * @return A formatted string
2789 * @see java.util.Formatter
2792 public static String format(String format, Object ... args) {
2793 throw new UnsupportedOperationException();
2797 * Returns a formatted string using the specified locale, format string,
2801 * The {@linkplain java.util.Locale locale} to apply during
2802 * formatting. If <tt>l</tt> is <tt>null</tt> then no localization
2806 * A <a href="../util/Formatter.html#syntax">format string</a>
2809 * Arguments referenced by the format specifiers in the format
2810 * string. If there are more arguments than format specifiers, the
2811 * extra arguments are ignored. The number of arguments is
2812 * variable and may be zero. The maximum number of arguments is
2813 * limited by the maximum dimension of a Java array as defined by
2814 * <cite>The Java™ Virtual Machine Specification</cite>.
2815 * The behaviour on a
2816 * <tt>null</tt> argument depends on the <a
2817 * href="../util/Formatter.html#syntax">conversion</a>.
2819 * @throws IllegalFormatException
2820 * If a format string contains an illegal syntax, a format
2821 * specifier that is incompatible with the given arguments,
2822 * insufficient arguments given the format string, or other
2823 * illegal conditions. For specification of all possible
2824 * formatting errors, see the <a
2825 * href="../util/Formatter.html#detail">Details</a> section of the
2826 * formatter class specification
2828 * @throws NullPointerException
2829 * If the <tt>format</tt> is <tt>null</tt>
2831 * @return A formatted string
2833 * @see java.util.Formatter
2836 // public static String format(Locale l, String format, Object ... args) {
2837 // return new Formatter(l).format(format, args).toString();
2841 * Returns the string representation of the <code>Object</code> argument.
2843 * @param obj an <code>Object</code>.
2844 * @return if the argument is <code>null</code>, then a string equal to
2845 * <code>"null"</code>; otherwise, the value of
2846 * <code>obj.toString()</code> is returned.
2847 * @see java.lang.Object#toString()
2849 public static String valueOf(Object obj) {
2850 return (obj == null) ? "null" : obj.toString();
2854 * Returns the string representation of the <code>char</code> array
2855 * argument. The contents of the character array are copied; subsequent
2856 * modification of the character array does not affect the newly
2859 * @param data a <code>char</code> array.
2860 * @return a newly allocated string representing the same sequence of
2861 * characters contained in the character array argument.
2863 public static String valueOf(char data[]) {
2864 return new String(data);
2868 * Returns the string representation of a specific subarray of the
2869 * <code>char</code> array argument.
2871 * The <code>offset</code> argument is the index of the first
2872 * character of the subarray. The <code>count</code> argument
2873 * specifies the length of the subarray. The contents of the subarray
2874 * are copied; subsequent modification of the character array does not
2875 * affect the newly created string.
2877 * @param data the character array.
2878 * @param offset the initial offset into the value of the
2879 * <code>String</code>.
2880 * @param count the length of the value of the <code>String</code>.
2881 * @return a string representing the sequence of characters contained
2882 * in the subarray of the character array argument.
2883 * @exception IndexOutOfBoundsException if <code>offset</code> is
2884 * negative, or <code>count</code> is negative, or
2885 * <code>offset+count</code> is larger than
2886 * <code>data.length</code>.
2888 public static String valueOf(char data[], int offset, int count) {
2889 return new String(data, offset, count);
2893 * Returns a String that represents the character sequence in the
2896 * @param data the character array.
2897 * @param offset initial offset of the subarray.
2898 * @param count length of the subarray.
2899 * @return a <code>String</code> that contains the characters of the
2900 * specified subarray of the character array.
2902 public static String copyValueOf(char data[], int offset, int count) {
2903 // All public String constructors now copy the data.
2904 return new String(data, offset, count);
2908 * Returns a String that represents the character sequence in the
2911 * @param data the character array.
2912 * @return a <code>String</code> that contains the characters of the
2915 public static String copyValueOf(char data[]) {
2916 return copyValueOf(data, 0, data.length);
2920 * Returns the string representation of the <code>boolean</code> argument.
2922 * @param b a <code>boolean</code>.
2923 * @return if the argument is <code>true</code>, a string equal to
2924 * <code>"true"</code> is returned; otherwise, a string equal to
2925 * <code>"false"</code> is returned.
2927 public static String valueOf(boolean b) {
2928 return b ? "true" : "false";
2932 * Returns the string representation of the <code>char</code>
2935 * @param c a <code>char</code>.
2936 * @return a string of length <code>1</code> containing
2937 * as its single character the argument <code>c</code>.
2939 public static String valueOf(char c) {
2941 return new String(data, 0, 1);
2945 * Returns the string representation of the <code>int</code> argument.
2947 * The representation is exactly the one returned by the
2948 * <code>Integer.toString</code> method of one argument.
2950 * @param i an <code>int</code>.
2951 * @return a string representation of the <code>int</code> argument.
2952 * @see java.lang.Integer#toString(int, int)
2954 public static String valueOf(int i) {
2955 return Integer.toString(i);
2959 * Returns the string representation of the <code>long</code> argument.
2961 * The representation is exactly the one returned by the
2962 * <code>Long.toString</code> method of one argument.
2964 * @param l a <code>long</code>.
2965 * @return a string representation of the <code>long</code> argument.
2966 * @see java.lang.Long#toString(long)
2968 public static String valueOf(long l) {
2969 return Long.toString(l);
2973 * Returns the string representation of the <code>float</code> argument.
2975 * The representation is exactly the one returned by the
2976 * <code>Float.toString</code> method of one argument.
2978 * @param f a <code>float</code>.
2979 * @return a string representation of the <code>float</code> argument.
2980 * @see java.lang.Float#toString(float)
2982 public static String valueOf(float f) {
2983 return Float.toString(f);
2987 * Returns the string representation of the <code>double</code> argument.
2989 * The representation is exactly the one returned by the
2990 * <code>Double.toString</code> method of one argument.
2992 * @param d a <code>double</code>.
2993 * @return a string representation of the <code>double</code> argument.
2994 * @see java.lang.Double#toString(double)
2996 public static String valueOf(double d) {
2997 return Double.toString(d);
3001 * Returns a canonical representation for the string object.
3003 * A pool of strings, initially empty, is maintained privately by the
3004 * class <code>String</code>.
3006 * When the intern method is invoked, if the pool already contains a
3007 * string equal to this <code>String</code> object as determined by
3008 * the {@link #equals(Object)} method, then the string from the pool is
3009 * returned. Otherwise, this <code>String</code> object is added to the
3010 * pool and a reference to this <code>String</code> object is returned.
3012 * It follows that for any two strings <code>s</code> and <code>t</code>,
3013 * <code>s.intern() == t.intern()</code> is <code>true</code>
3014 * if and only if <code>s.equals(t)</code> is <code>true</code>.
3016 * All literal strings and string-valued constant expressions are
3017 * interned. String literals are defined in section 3.10.5 of the
3018 * <cite>The Java™ Language Specification</cite>.
3020 * @return a string that has the same contents as this string, but is
3021 * guaranteed to be from a pool of unique strings.
3023 public native String intern();