Moving modules around so the runtime is under one master pom and can be built without building other modules that are in the repository
2 * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
28 import java.io.UnsupportedEncodingException;
29 import java.util.Comparator;
30 import org.apidesign.bck2brwsr.core.ExtraJavaScript;
31 import org.apidesign.bck2brwsr.core.JavaScriptBody;
32 import org.apidesign.bck2brwsr.core.JavaScriptOnly;
33 import org.apidesign.bck2brwsr.core.JavaScriptPrototype;
34 import org.apidesign.bck2brwsr.emul.lang.System;
37 * The <code>String</code> class represents character strings. All
38 * string literals in Java programs, such as <code>"abc"</code>, are
39 * implemented as instances of this class.
41 * Strings are constant; their values cannot be changed after they
42 * are created. String buffers support mutable strings.
43 * Because String objects are immutable they can be shared. For example:
44 * <p><blockquote><pre>
46 * </pre></blockquote><p>
48 * <p><blockquote><pre>
49 * char data[] = {'a', 'b', 'c'};
50 * String str = new String(data);
51 * </pre></blockquote><p>
52 * Here are some more examples of how strings can be used:
53 * <p><blockquote><pre>
54 * System.out.println("abc");
56 * System.out.println("abc" + cde);
57 * String c = "abc".substring(2,3);
58 * String d = cde.substring(1, 2);
61 * The class <code>String</code> includes methods for examining
62 * individual characters of the sequence, for comparing strings, for
63 * searching strings, for extracting substrings, and for creating a
64 * copy of a string with all characters translated to uppercase or to
65 * lowercase. Case mapping is based on the Unicode Standard version
66 * specified by the {@link java.lang.Character Character} class.
68 * The Java language provides special support for the string
69 * concatenation operator ( + ), and for conversion of
70 * other objects to strings. String concatenation is implemented
71 * through the <code>StringBuilder</code>(or <code>StringBuffer</code>)
72 * class and its <code>append</code> method.
73 * String conversions are implemented through the method
74 * <code>toString</code>, defined by <code>Object</code> and
75 * inherited by all classes in Java. For additional information on
76 * string concatenation and conversion, see Gosling, Joy, and Steele,
77 * <i>The Java Language Specification</i>.
79 * <p> Unless otherwise noted, passing a <tt>null</tt> argument to a constructor
80 * or method in this class will cause a {@link NullPointerException} to be
83 * <p>A <code>String</code> represents a string in the UTF-16 format
84 * in which <em>supplementary characters</em> are represented by <em>surrogate
85 * pairs</em> (see the section <a href="Character.html#unicode">Unicode
86 * Character Representations</a> in the <code>Character</code> class for
88 * Index values refer to <code>char</code> code units, so a supplementary
89 * character uses two positions in a <code>String</code>.
90 * <p>The <code>String</code> class provides methods for dealing with
91 * Unicode code points (i.e., characters), in addition to those for
92 * dealing with Unicode code units (i.e., <code>char</code> values).
95 * @author Arthur van Hoff
96 * @author Martin Buchholz
98 * @see java.lang.Object#toString()
99 * @see java.lang.StringBuffer
100 * @see java.lang.StringBuilder
101 * @see java.nio.charset.Charset
106 resource="/org/apidesign/vm4brwsr/emul/lang/java_lang_String.js",
109 @JavaScriptPrototype(container = "String.prototype", prototype = "new String")
110 public final class String
111 implements java.io.Serializable, Comparable<String>, CharSequence
113 /** real string to delegate to */
116 /** use serialVersionUID from JDK 1.0.2 for interoperability */
117 private static final long serialVersionUID = -6849794470754667710L;
119 @JavaScriptOnly(name="toString", value="String.prototype._r")
120 private static void jsToString() {
123 @JavaScriptOnly(name="valueOf", value="function() { return this.toString().valueOf(); }")
124 private static void jsValudOf() {
128 * Class String is special cased within the Serialization Stream Protocol.
130 * A String instance is written initially into an ObjectOutputStream in the
133 * <code>TC_STRING</code> (utf String)
135 * The String is written by method <code>DataOutput.writeUTF</code>.
136 * A new handle is generated to refer to all future references to the
137 * string instance within the stream.
139 // private static final ObjectStreamField[] serialPersistentFields =
140 // new ObjectStreamField[0];
143 * Initializes a newly created {@code String} object so that it represents
144 * an empty character sequence. Note that use of this constructor is
145 * unnecessary since Strings are immutable.
152 * Initializes a newly created {@code String} object so that it represents
153 * the same sequence of characters as the argument; in other words, the
154 * newly created string is a copy of the argument string. Unless an
155 * explicit copy of {@code original} is needed, use of this constructor is
156 * unnecessary since Strings are immutable.
161 public String(String original) {
162 this.r = original.toString();
166 * Allocates a new {@code String} so that it represents the sequence of
167 * characters currently contained in the character array argument. The
168 * contents of the character array are copied; subsequent modification of
169 * the character array does not affect the newly created string.
172 * The initial value of the string
174 @JavaScriptBody(args = { "charArr" }, body=
175 "for (var i = 0; i < charArr.length; i++) {\n"
176 + " if (typeof charArr[i] === 'number') charArr[i] = String.fromCharCode(charArr[i]);\n"
178 + "this._r(charArr.join(''));\n"
180 public String(char value[]) {
184 * Allocates a new {@code String} that contains characters from a subarray
185 * of the character array argument. The {@code offset} argument is the
186 * index of the first character of the subarray and the {@code count}
187 * argument specifies the length of the subarray. The contents of the
188 * subarray are copied; subsequent modification of the character array does
189 * not affect the newly created string.
192 * Array that is the source of characters
200 * @throws IndexOutOfBoundsException
201 * If the {@code offset} and {@code count} arguments index
202 * characters outside the bounds of the {@code value} array
204 public String(char value[], int offset, int count) {
205 initFromCharArray(value, offset, count);
208 @JavaScriptBody(args = { "charArr", "off", "cnt" }, body =
209 "var up = off + cnt;\n" +
210 "for (var i = off; i < up; i++) {\n" +
211 " if (typeof charArr[i] === 'number') charArr[i] = String.fromCharCode(charArr[i]);\n" +
213 "this._r(charArr.slice(off, up).join(\"\"));\n"
215 private native void initFromCharArray(char value[], int offset, int count);
218 * Allocates a new {@code String} that contains characters from a subarray
219 * of the <a href="Character.html#unicode">Unicode code point</a> array
220 * argument. The {@code offset} argument is the index of the first code
221 * point of the subarray and the {@code count} argument specifies the
222 * length of the subarray. The contents of the subarray are converted to
223 * {@code char}s; subsequent modification of the {@code int} array does not
224 * affect the newly created string.
227 * Array that is the source of Unicode code points
235 * @throws IllegalArgumentException
236 * If any invalid Unicode code point is found in {@code
239 * @throws IndexOutOfBoundsException
240 * If the {@code offset} and {@code count} arguments index
241 * characters outside the bounds of the {@code codePoints} array
245 public String(int[] codePoints, int offset, int count) {
247 throw new StringIndexOutOfBoundsException(offset);
250 throw new StringIndexOutOfBoundsException(count);
252 // Note: offset or count might be near -1>>>1.
253 if (offset > codePoints.length - count) {
254 throw new StringIndexOutOfBoundsException(offset + count);
257 final int end = offset + count;
259 // Pass 1: Compute precise size of char[]
261 for (int i = offset; i < end; i++) {
262 int c = codePoints[i];
263 if (Character.isBmpCodePoint(c))
265 else if (Character.isValidCodePoint(c))
267 else throw new IllegalArgumentException(Integer.toString(c));
270 // Pass 2: Allocate and fill in char[]
271 final char[] v = new char[n];
273 for (int i = offset, j = 0; i < end; i++, j++) {
274 int c = codePoints[i];
275 if (Character.isBmpCodePoint(c))
278 Character.toSurrogates(c, v, j++);
281 this.r = new String(v, 0, n);
285 * Allocates a new {@code String} constructed from a subarray of an array
286 * of 8-bit integer values.
288 * <p> The {@code offset} argument is the index of the first byte of the
289 * subarray, and the {@code count} argument specifies the length of the
292 * <p> Each {@code byte} in the subarray is converted to a {@code char} as
293 * specified in the method above.
295 * @deprecated This method does not properly convert bytes into characters.
296 * As of JDK 1.1, the preferred way to do this is via the
297 * {@code String} constructors that take a {@link
298 * java.nio.charset.Charset}, charset name, or that use the platform's
302 * The bytes to be converted to characters
305 * The top 8 bits of each 16-bit Unicode code unit
312 * @throws IndexOutOfBoundsException
313 * If the {@code offset} or {@code count} argument is invalid
315 * @see #String(byte[], int)
316 * @see #String(byte[], int, int, java.lang.String)
317 * @see #String(byte[], int, int, java.nio.charset.Charset)
318 * @see #String(byte[], int, int)
319 * @see #String(byte[], java.lang.String)
320 * @see #String(byte[], java.nio.charset.Charset)
321 * @see #String(byte[])
324 public String(byte ascii[], int hibyte, int offset, int count) {
325 checkBounds(ascii, offset, count);
326 char value[] = new char[count];
329 for (int i = count ; i-- > 0 ;) {
330 value[i] = (char) (ascii[i + offset] & 0xff);
334 for (int i = count ; i-- > 0 ;) {
335 value[i] = (char) (hibyte | (ascii[i + offset] & 0xff));
338 initFromCharArray(value, offset, count);
342 * Allocates a new {@code String} containing characters constructed from
343 * an array of 8-bit integer values. Each character <i>c</i>in the
344 * resulting string is constructed from the corresponding component
345 * <i>b</i> in the byte array such that:
348 * <b><i>c</i></b> == (char)(((hibyte & 0xff) << 8)
349 * | (<b><i>b</i></b> & 0xff))
350 * </pre></blockquote>
352 * @deprecated This method does not properly convert bytes into
353 * characters. As of JDK 1.1, the preferred way to do this is via the
354 * {@code String} constructors that take a {@link
355 * java.nio.charset.Charset}, charset name, or that use the platform's
359 * The bytes to be converted to characters
362 * The top 8 bits of each 16-bit Unicode code unit
364 * @see #String(byte[], int, int, java.lang.String)
365 * @see #String(byte[], int, int, java.nio.charset.Charset)
366 * @see #String(byte[], int, int)
367 * @see #String(byte[], java.lang.String)
368 * @see #String(byte[], java.nio.charset.Charset)
369 * @see #String(byte[])
372 public String(byte ascii[], int hibyte) {
373 this(ascii, hibyte, 0, ascii.length);
376 /* Common private utility method used to bounds check the byte array
377 * and requested offset & length values used by the String(byte[],..)
380 private static void checkBounds(byte[] bytes, int offset, int length) {
382 throw new StringIndexOutOfBoundsException(length);
384 throw new StringIndexOutOfBoundsException(offset);
385 if (offset > bytes.length - length)
386 throw new StringIndexOutOfBoundsException(offset + length);
390 * Constructs a new {@code String} by decoding the specified subarray of
391 * bytes using the specified charset. The length of the new {@code String}
392 * is a function of the charset, and hence may not be equal to the length
395 * <p> The behavior of this constructor when the given bytes are not valid
396 * in the given charset is unspecified. The {@link
397 * java.nio.charset.CharsetDecoder} class should be used when more control
398 * over the decoding process is required.
401 * The bytes to be decoded into characters
404 * The index of the first byte to decode
407 * The number of bytes to decode
410 * The name of a supported {@linkplain java.nio.charset.Charset
413 * @throws UnsupportedEncodingException
414 * If the named charset is not supported
416 * @throws IndexOutOfBoundsException
417 * If the {@code offset} and {@code length} arguments index
418 * characters outside the bounds of the {@code bytes} array
422 public String(byte bytes[], int offset, int length, String charsetName)
423 throws UnsupportedEncodingException
425 this(checkUTF8(bytes, charsetName), offset, length);
429 * Constructs a new {@code String} by decoding the specified subarray of
430 * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
431 * The length of the new {@code String} is a function of the charset, and
432 * hence may not be equal to the length of the subarray.
434 * <p> This method always replaces malformed-input and unmappable-character
435 * sequences with this charset's default replacement string. The {@link
436 * java.nio.charset.CharsetDecoder} class should be used when more control
437 * over the decoding process is required.
440 * The bytes to be decoded into characters
443 * The index of the first byte to decode
446 * The number of bytes to decode
449 * The {@linkplain java.nio.charset.Charset charset} to be used to
450 * decode the {@code bytes}
452 * @throws IndexOutOfBoundsException
453 * If the {@code offset} and {@code length} arguments index
454 * characters outside the bounds of the {@code bytes} array
458 /* don't want dependnecy on Charset
459 public String(byte bytes[], int offset, int length, Charset charset) {
461 throw new NullPointerException("charset");
462 checkBounds(bytes, offset, length);
463 char[] v = StringCoding.decode(charset, bytes, offset, length);
465 this.count = v.length;
471 * Constructs a new {@code String} by decoding the specified array of bytes
472 * using the specified {@linkplain java.nio.charset.Charset charset}. The
473 * length of the new {@code String} is a function of the charset, and hence
474 * may not be equal to the length of the byte array.
476 * <p> The behavior of this constructor when the given bytes are not valid
477 * in the given charset is unspecified. The {@link
478 * java.nio.charset.CharsetDecoder} class should be used when more control
479 * over the decoding process is required.
482 * The bytes to be decoded into characters
485 * The name of a supported {@linkplain java.nio.charset.Charset
488 * @throws UnsupportedEncodingException
489 * If the named charset is not supported
493 public String(byte bytes[], String charsetName)
494 throws UnsupportedEncodingException
496 this(bytes, 0, bytes.length, charsetName);
500 * Constructs a new {@code String} by decoding the specified array of
501 * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
502 * The length of the new {@code String} is a function of the charset, and
503 * hence may not be equal to the length of the byte array.
505 * <p> This method always replaces malformed-input and unmappable-character
506 * sequences with this charset's default replacement string. The {@link
507 * java.nio.charset.CharsetDecoder} class should be used when more control
508 * over the decoding process is required.
511 * The bytes to be decoded into characters
514 * The {@linkplain java.nio.charset.Charset charset} to be used to
515 * decode the {@code bytes}
519 /* don't want dep on Charset
520 public String(byte bytes[], Charset charset) {
521 this(bytes, 0, bytes.length, charset);
526 * Constructs a new {@code String} by decoding the specified subarray of
527 * bytes using the platform's default charset. The length of the new
528 * {@code String} is a function of the charset, and hence may not be equal
529 * to the length of the subarray.
531 * <p> The behavior of this constructor when the given bytes are not valid
532 * in the default charset is unspecified. The {@link
533 * java.nio.charset.CharsetDecoder} class should be used when more control
534 * over the decoding process is required.
537 * The bytes to be decoded into characters
540 * The index of the first byte to decode
543 * The number of bytes to decode
545 * @throws IndexOutOfBoundsException
546 * If the {@code offset} and the {@code length} arguments index
547 * characters outside the bounds of the {@code bytes} array
551 public String(byte bytes[], int offset, int length) {
552 checkBounds(bytes, offset, length);
553 char[] v = new char[length];
554 int[] at = { offset };
555 int end = offset + length;
557 while (at[0] < end) {
558 int ch = nextChar(bytes, at);
559 v[chlen++] = (char)ch;
561 initFromCharArray(v, 0, chlen);
565 * Constructs a new {@code String} by decoding the specified array of bytes
566 * using the platform's default charset. The length of the new {@code
567 * String} is a function of the charset, and hence may not be equal to the
568 * length of the byte array.
570 * <p> The behavior of this constructor when the given bytes are not valid
571 * in the default charset is unspecified. The {@link
572 * java.nio.charset.CharsetDecoder} class should be used when more control
573 * over the decoding process is required.
576 * The bytes to be decoded into characters
580 public String(byte bytes[]) {
581 this(bytes, 0, bytes.length);
585 * Allocates a new string that contains the sequence of characters
586 * currently contained in the string buffer argument. The contents of the
587 * string buffer are copied; subsequent modification of the string buffer
588 * does not affect the newly created string.
591 * A {@code StringBuffer}
593 public String(StringBuffer buffer) {
594 this.r = buffer.toString();
598 * Allocates a new string that contains the sequence of characters
599 * currently contained in the string builder argument. The contents of the
600 * string builder are copied; subsequent modification of the string builder
601 * does not affect the newly created string.
603 * <p> This constructor is provided to ease migration to {@code
604 * StringBuilder}. Obtaining a string from a string builder via the {@code
605 * toString} method is likely to run faster and is generally preferred.
608 * A {@code StringBuilder}
612 public String(StringBuilder builder) {
613 this.r = builder.toString();
617 * Returns the length of this string.
618 * The length is equal to the number of <a href="Character.html#unicode">Unicode
619 * code units</a> in the string.
621 * @return the length of the sequence of characters represented by this
624 @JavaScriptBody(args = {}, body = "return this.toString().length;")
625 public int length() {
626 throw new UnsupportedOperationException();
630 * Returns <tt>true</tt> if, and only if, {@link #length()} is <tt>0</tt>.
632 * @return <tt>true</tt> if {@link #length()} is <tt>0</tt>, otherwise
637 @JavaScriptBody(args = {}, body="return this.toString().length === 0;")
638 public boolean isEmpty() {
639 return length() == 0;
643 * Returns the <code>char</code> value at the
644 * specified index. An index ranges from <code>0</code> to
645 * <code>length() - 1</code>. The first <code>char</code> value of the sequence
646 * is at index <code>0</code>, the next at index <code>1</code>,
647 * and so on, as for array indexing.
649 * <p>If the <code>char</code> value specified by the index is a
650 * <a href="Character.html#unicode">surrogate</a>, the surrogate
653 * @param index the index of the <code>char</code> value.
654 * @return the <code>char</code> value at the specified index of this string.
655 * The first <code>char</code> value is at index <code>0</code>.
656 * @exception IndexOutOfBoundsException if the <code>index</code>
657 * argument is negative or not less than the length of this
660 @JavaScriptBody(args = { "index" },
661 body = "return this.toString().charCodeAt(index);"
663 public char charAt(int index) {
664 throw new UnsupportedOperationException();
668 * Returns the character (Unicode code point) at the specified
669 * index. The index refers to <code>char</code> values
670 * (Unicode code units) and ranges from <code>0</code> to
671 * {@link #length()}<code> - 1</code>.
673 * <p> If the <code>char</code> value specified at the given index
674 * is in the high-surrogate range, the following index is less
675 * than the length of this <code>String</code>, and the
676 * <code>char</code> value at the following index is in the
677 * low-surrogate range, then the supplementary code point
678 * corresponding to this surrogate pair is returned. Otherwise,
679 * the <code>char</code> value at the given index is returned.
681 * @param index the index to the <code>char</code> values
682 * @return the code point value of the character at the
684 * @exception IndexOutOfBoundsException if the <code>index</code>
685 * argument is negative or not less than the length of this
689 public int codePointAt(int index) {
690 if ((index < 0) || (index >= length())) {
691 throw new StringIndexOutOfBoundsException(index);
693 return Character.codePointAtImpl(toCharArray(), offset() + index, offset() + length());
697 * Returns the character (Unicode code point) before the specified
698 * index. The index refers to <code>char</code> values
699 * (Unicode code units) and ranges from <code>1</code> to {@link
700 * CharSequence#length() length}.
702 * <p> If the <code>char</code> value at <code>(index - 1)</code>
703 * is in the low-surrogate range, <code>(index - 2)</code> is not
704 * negative, and the <code>char</code> value at <code>(index -
705 * 2)</code> is in the high-surrogate range, then the
706 * supplementary code point value of the surrogate pair is
707 * returned. If the <code>char</code> value at <code>index -
708 * 1</code> is an unpaired low-surrogate or a high-surrogate, the
709 * surrogate value is returned.
711 * @param index the index following the code point that should be returned
712 * @return the Unicode code point value before the given index.
713 * @exception IndexOutOfBoundsException if the <code>index</code>
714 * argument is less than 1 or greater than the length
718 public int codePointBefore(int index) {
720 if ((i < 0) || (i >= length())) {
721 throw new StringIndexOutOfBoundsException(index);
723 return Character.codePointBeforeImpl(toCharArray(), offset() + index, offset());
727 * Returns the number of Unicode code points in the specified text
728 * range of this <code>String</code>. The text range begins at the
729 * specified <code>beginIndex</code> and extends to the
730 * <code>char</code> at index <code>endIndex - 1</code>. Thus the
731 * length (in <code>char</code>s) of the text range is
732 * <code>endIndex-beginIndex</code>. Unpaired surrogates within
733 * the text range count as one code point each.
735 * @param beginIndex the index to the first <code>char</code> of
737 * @param endIndex the index after the last <code>char</code> of
739 * @return the number of Unicode code points in the specified text
741 * @exception IndexOutOfBoundsException if the
742 * <code>beginIndex</code> is negative, or <code>endIndex</code>
743 * is larger than the length of this <code>String</code>, or
744 * <code>beginIndex</code> is larger than <code>endIndex</code>.
747 public int codePointCount(int beginIndex, int endIndex) {
748 if (beginIndex < 0 || endIndex > length() || beginIndex > endIndex) {
749 throw new IndexOutOfBoundsException();
751 return Character.codePointCountImpl(toCharArray(), offset()+beginIndex, endIndex-beginIndex);
755 * Returns the index within this <code>String</code> that is
756 * offset from the given <code>index</code> by
757 * <code>codePointOffset</code> code points. Unpaired surrogates
758 * within the text range given by <code>index</code> and
759 * <code>codePointOffset</code> count as one code point each.
761 * @param index the index to be offset
762 * @param codePointOffset the offset in code points
763 * @return the index within this <code>String</code>
764 * @exception IndexOutOfBoundsException if <code>index</code>
765 * is negative or larger then the length of this
766 * <code>String</code>, or if <code>codePointOffset</code> is positive
767 * and the substring starting with <code>index</code> has fewer
768 * than <code>codePointOffset</code> code points,
769 * or if <code>codePointOffset</code> is negative and the substring
770 * before <code>index</code> has fewer than the absolute value
771 * of <code>codePointOffset</code> code points.
774 public int offsetByCodePoints(int index, int codePointOffset) {
775 if (index < 0 || index > length()) {
776 throw new IndexOutOfBoundsException();
778 return Character.offsetByCodePointsImpl(toCharArray(), offset(), length(),
779 offset()+index, codePointOffset) - offset();
783 * Copy characters from this string into dst starting at dstBegin.
784 * This method doesn't perform any range checking.
786 @JavaScriptBody(args = { "arr", "to" }, body =
787 "var s = this.toString();\n" +
788 "for (var i = 0; i < s.length; i++) {\n" +
789 " arr[to++] = s[i];\n" +
792 void getChars(char dst[], int dstBegin) {
793 System.arraycopy(toCharArray(), offset(), dst, dstBegin, length());
797 * Copies characters from this string into the destination character
800 * The first character to be copied is at index <code>srcBegin</code>;
801 * the last character to be copied is at index <code>srcEnd-1</code>
802 * (thus the total number of characters to be copied is
803 * <code>srcEnd-srcBegin</code>). The characters are copied into the
804 * subarray of <code>dst</code> starting at index <code>dstBegin</code>
805 * and ending at index:
806 * <p><blockquote><pre>
807 * dstbegin + (srcEnd-srcBegin) - 1
808 * </pre></blockquote>
810 * @param srcBegin index of the first character in the string
812 * @param srcEnd index after the last character in the string
814 * @param dst the destination array.
815 * @param dstBegin the start offset in the destination array.
816 * @exception IndexOutOfBoundsException If any of the following
818 * <ul><li><code>srcBegin</code> is negative.
819 * <li><code>srcBegin</code> is greater than <code>srcEnd</code>
820 * <li><code>srcEnd</code> is greater than the length of this
822 * <li><code>dstBegin</code> is negative
823 * <li><code>dstBegin+(srcEnd-srcBegin)</code> is larger than
824 * <code>dst.length</code></ul>
826 @JavaScriptBody(args = { "beg", "end", "arr", "dst" }, body=
827 "var s = this.toString();\n" +
828 "while (beg < end) {\n" +
829 " arr[dst++] = s.charCodeAt(beg++);\n" +
832 public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
834 throw new StringIndexOutOfBoundsException(srcBegin);
836 if (srcEnd > length()) {
837 throw new StringIndexOutOfBoundsException(srcEnd);
839 if (srcBegin > srcEnd) {
840 throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
842 System.arraycopy(toCharArray(), offset() + srcBegin, dst, dstBegin,
847 * Copies characters from this string into the destination byte array. Each
848 * byte receives the 8 low-order bits of the corresponding character. The
849 * eight high-order bits of each character are not copied and do not
850 * participate in the transfer in any way.
852 * <p> The first character to be copied is at index {@code srcBegin}; the
853 * last character to be copied is at index {@code srcEnd-1}. The total
854 * number of characters to be copied is {@code srcEnd-srcBegin}. The
855 * characters, converted to bytes, are copied into the subarray of {@code
856 * dst} starting at index {@code dstBegin} and ending at index:
859 * dstbegin + (srcEnd-srcBegin) - 1
860 * </pre></blockquote>
862 * @deprecated This method does not properly convert characters into
863 * bytes. As of JDK 1.1, the preferred way to do this is via the
864 * {@link #getBytes()} method, which uses the platform's default charset.
867 * Index of the first character in the string to copy
870 * Index after the last character in the string to copy
873 * The destination array
876 * The start offset in the destination array
878 * @throws IndexOutOfBoundsException
879 * If any of the following is true:
881 * <li> {@code srcBegin} is negative
882 * <li> {@code srcBegin} is greater than {@code srcEnd}
883 * <li> {@code srcEnd} is greater than the length of this String
884 * <li> {@code dstBegin} is negative
885 * <li> {@code dstBegin+(srcEnd-srcBegin)} is larger than {@code
890 public void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin) {
892 throw new StringIndexOutOfBoundsException(srcBegin);
894 if (srcEnd > length()) {
895 throw new StringIndexOutOfBoundsException(srcEnd);
897 if (srcBegin > srcEnd) {
898 throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
901 int n = offset() + srcEnd;
902 int i = offset() + srcBegin;
903 char[] val = toCharArray(); /* avoid getfield opcode */
906 dst[j++] = (byte)val[i++];
911 * Encodes this {@code String} into a sequence of bytes using the named
912 * charset, storing the result into a new byte array.
914 * <p> The behavior of this method when this string cannot be encoded in
915 * the given charset is unspecified. The {@link
916 * java.nio.charset.CharsetEncoder} class should be used when more control
917 * over the encoding process is required.
920 * The name of a supported {@linkplain java.nio.charset.Charset
923 * @return The resultant byte array
925 * @throws UnsupportedEncodingException
926 * If the named charset is not supported
930 public byte[] getBytes(String charsetName)
931 throws UnsupportedEncodingException
933 checkUTF8(null, charsetName);
938 * Encodes this {@code String} into a sequence of bytes using the given
939 * {@linkplain java.nio.charset.Charset charset}, storing the result into a
942 * <p> This method always replaces malformed-input and unmappable-character
943 * sequences with this charset's default replacement byte array. The
944 * {@link java.nio.charset.CharsetEncoder} class should be used when more
945 * control over the encoding process is required.
948 * The {@linkplain java.nio.charset.Charset} to be used to encode
951 * @return The resultant byte array
955 /* don't want dep on Charset
956 public byte[] getBytes(Charset charset) {
957 if (charset == null) throw new NullPointerException();
958 return StringCoding.encode(charset, value, offset, count);
963 * Encodes this {@code String} into a sequence of bytes using the
964 * platform's default charset, storing the result into a new byte array.
966 * <p> The behavior of this method when this string cannot be encoded in
967 * the default charset is unspecified. The {@link
968 * java.nio.charset.CharsetEncoder} class should be used when more control
969 * over the encoding process is required.
971 * @return The resultant byte array
975 public byte[] getBytes() {
977 byte[] arr = new byte[len];
978 for (int i = 0, j = 0; j < len; j++) {
979 final int v = charAt(j);
985 arr = System.expandArray(arr, i + 1);
986 arr[i++] = (byte) (0xC0 | (v >> 6));
987 arr[i++] = (byte) (0x80 | (0x3F & v));
990 arr = System.expandArray(arr, i + 2);
991 arr[i++] = (byte) (0xE0 | (v >> 12));
992 arr[i++] = (byte) (0x80 | ((v >> 6) & 0x7F));
993 arr[i++] = (byte) (0x80 | (0x3F & v));
999 * Compares this string to the specified object. The result is {@code
1000 * true} if and only if the argument is not {@code null} and is a {@code
1001 * String} object that represents the same sequence of characters as this
1005 * The object to compare this {@code String} against
1007 * @return {@code true} if the given object represents a {@code String}
1008 * equivalent to this string, {@code false} otherwise
1010 * @see #compareTo(String)
1011 * @see #equalsIgnoreCase(String)
1013 @JavaScriptBody(args = { "obj" }, body =
1014 "return obj != null && obj.$instOf_java_lang_String && "
1015 + "this.toString() === obj.toString();"
1017 public boolean equals(Object anObject) {
1018 if (this == anObject) {
1021 if (anObject instanceof String) {
1022 String anotherString = (String)anObject;
1024 if (n == anotherString.length()) {
1025 char v1[] = toCharArray();
1026 char v2[] = anotherString.toCharArray();
1028 int j = anotherString.offset();
1030 if (v1[i++] != v2[j++])
1040 * Compares this string to the specified {@code StringBuffer}. The result
1041 * is {@code true} if and only if this {@code String} represents the same
1042 * sequence of characters as the specified {@code StringBuffer}.
1045 * The {@code StringBuffer} to compare this {@code String} against
1047 * @return {@code true} if this {@code String} represents the same
1048 * sequence of characters as the specified {@code StringBuffer},
1049 * {@code false} otherwise
1053 public boolean contentEquals(StringBuffer sb) {
1055 return contentEquals((CharSequence)sb);
1060 * Compares this string to the specified {@code CharSequence}. The result
1061 * is {@code true} if and only if this {@code String} represents the same
1062 * sequence of char values as the specified sequence.
1065 * The sequence to compare this {@code String} against
1067 * @return {@code true} if this {@code String} represents the same
1068 * sequence of char values as the specified sequence, {@code
1073 public boolean contentEquals(CharSequence cs) {
1074 if (length() != cs.length())
1076 // Argument is a StringBuffer, StringBuilder
1077 if (cs instanceof AbstractStringBuilder) {
1078 char v1[] = toCharArray();
1079 char v2[] = ((AbstractStringBuilder)cs).getValue();
1084 if (v1[i++] != v2[j++])
1089 // Argument is a String
1090 if (cs.equals(this))
1092 // Argument is a generic CharSequence
1093 char v1[] = toCharArray();
1098 if (v1[i++] != cs.charAt(j++))
1105 * Compares this {@code String} to another {@code String}, ignoring case
1106 * considerations. Two strings are considered equal ignoring case if they
1107 * are of the same length and corresponding characters in the two strings
1108 * are equal ignoring case.
1110 * <p> Two characters {@code c1} and {@code c2} are considered the same
1111 * ignoring case if at least one of the following is true:
1113 * <li> The two characters are the same (as compared by the
1114 * {@code ==} operator)
1115 * <li> Applying the method {@link
1116 * java.lang.Character#toUpperCase(char)} to each character
1117 * produces the same result
1118 * <li> Applying the method {@link
1119 * java.lang.Character#toLowerCase(char)} to each character
1120 * produces the same result
1123 * @param anotherString
1124 * The {@code String} to compare this {@code String} against
1126 * @return {@code true} if the argument is not {@code null} and it
1127 * represents an equivalent {@code String} ignoring case; {@code
1130 * @see #equals(Object)
1132 public boolean equalsIgnoreCase(String anotherString) {
1133 return (this == anotherString) ? true :
1134 (anotherString != null) && (anotherString.length() == length()) &&
1135 regionMatches(true, 0, anotherString, 0, length());
1139 * Compares two strings lexicographically.
1140 * The comparison is based on the Unicode value of each character in
1141 * the strings. The character sequence represented by this
1142 * <code>String</code> object is compared lexicographically to the
1143 * character sequence represented by the argument string. The result is
1144 * a negative integer if this <code>String</code> object
1145 * lexicographically precedes the argument string. The result is a
1146 * positive integer if this <code>String</code> object lexicographically
1147 * follows the argument string. The result is zero if the strings
1148 * are equal; <code>compareTo</code> returns <code>0</code> exactly when
1149 * the {@link #equals(Object)} method would return <code>true</code>.
1151 * This is the definition of lexicographic ordering. If two strings are
1152 * different, then either they have different characters at some index
1153 * that is a valid index for both strings, or their lengths are different,
1154 * or both. If they have different characters at one or more index
1155 * positions, let <i>k</i> be the smallest such index; then the string
1156 * whose character at position <i>k</i> has the smaller value, as
1157 * determined by using the < operator, lexicographically precedes the
1158 * other string. In this case, <code>compareTo</code> returns the
1159 * difference of the two character values at position <code>k</code> in
1160 * the two string -- that is, the value:
1162 * this.charAt(k)-anotherString.charAt(k)
1163 * </pre></blockquote>
1164 * If there is no index position at which they differ, then the shorter
1165 * string lexicographically precedes the longer string. In this case,
1166 * <code>compareTo</code> returns the difference of the lengths of the
1167 * strings -- that is, the value:
1169 * this.length()-anotherString.length()
1170 * </pre></blockquote>
1172 * @param anotherString the <code>String</code> to be compared.
1173 * @return the value <code>0</code> if the argument string is equal to
1174 * this string; a value less than <code>0</code> if this string
1175 * is lexicographically less than the string argument; and a
1176 * value greater than <code>0</code> if this string is
1177 * lexicographically greater than the string argument.
1179 public int compareTo(String anotherString) {
1180 int len1 = length();
1181 int len2 = anotherString.length();
1182 int n = Math.min(len1, len2);
1183 char v1[] = toCharArray();
1184 char v2[] = anotherString.toCharArray();
1186 int j = anotherString.offset();
1212 * A Comparator that orders <code>String</code> objects as by
1213 * <code>compareToIgnoreCase</code>. This comparator is serializable.
1215 * Note that this Comparator does <em>not</em> take locale into account,
1216 * and will result in an unsatisfactory ordering for certain locales.
1217 * The java.text package provides <em>Collators</em> to allow
1218 * locale-sensitive ordering.
1220 * @see java.text.Collator#compare(String, String)
1223 public static final Comparator<String> CASE_INSENSITIVE_ORDER
1224 = new CaseInsensitiveComparator();
1226 private static int offset() {
1230 private static class CaseInsensitiveComparator
1231 implements Comparator<String>, java.io.Serializable {
1232 // use serialVersionUID from JDK 1.2.2 for interoperability
1233 private static final long serialVersionUID = 8575799808933029326L;
1235 public int compare(String s1, String s2) {
1236 int n1 = s1.length();
1237 int n2 = s2.length();
1238 int min = Math.min(n1, n2);
1239 for (int i = 0; i < min; i++) {
1240 char c1 = s1.charAt(i);
1241 char c2 = s2.charAt(i);
1243 c1 = Character.toUpperCase(c1);
1244 c2 = Character.toUpperCase(c2);
1246 c1 = Character.toLowerCase(c1);
1247 c2 = Character.toLowerCase(c2);
1249 // No overflow because of numeric promotion
1260 * Compares two strings lexicographically, ignoring case
1261 * differences. This method returns an integer whose sign is that of
1262 * calling <code>compareTo</code> with normalized versions of the strings
1263 * where case differences have been eliminated by calling
1264 * <code>Character.toLowerCase(Character.toUpperCase(character))</code> on
1267 * Note that this method does <em>not</em> take locale into account,
1268 * and will result in an unsatisfactory ordering for certain locales.
1269 * The java.text package provides <em>collators</em> to allow
1270 * locale-sensitive ordering.
1272 * @param str the <code>String</code> to be compared.
1273 * @return a negative integer, zero, or a positive integer as the
1274 * specified String is greater than, equal to, or less
1275 * than this String, ignoring case considerations.
1276 * @see java.text.Collator#compare(String, String)
1279 public int compareToIgnoreCase(String str) {
1280 return CASE_INSENSITIVE_ORDER.compare(this, str);
1284 * Tests if two string regions are equal.
1286 * A substring of this <tt>String</tt> object is compared to a substring
1287 * of the argument other. The result is true if these substrings
1288 * represent identical character sequences. The substring of this
1289 * <tt>String</tt> object to be compared begins at index <tt>toffset</tt>
1290 * and has length <tt>len</tt>. The substring of other to be compared
1291 * begins at index <tt>ooffset</tt> and has length <tt>len</tt>. The
1292 * result is <tt>false</tt> if and only if at least one of the following
1294 * <ul><li><tt>toffset</tt> is negative.
1295 * <li><tt>ooffset</tt> is negative.
1296 * <li><tt>toffset+len</tt> is greater than the length of this
1297 * <tt>String</tt> object.
1298 * <li><tt>ooffset+len</tt> is greater than the length of the other
1300 * <li>There is some nonnegative integer <i>k</i> less than <tt>len</tt>
1302 * <tt>this.charAt(toffset+<i>k</i>) != other.charAt(ooffset+<i>k</i>)</tt>
1305 * @param toffset the starting offset of the subregion in this string.
1306 * @param other the string argument.
1307 * @param ooffset the starting offset of the subregion in the string
1309 * @param len the number of characters to compare.
1310 * @return <code>true</code> if the specified subregion of this string
1311 * exactly matches the specified subregion of the string argument;
1312 * <code>false</code> otherwise.
1314 public boolean regionMatches(int toffset, String other, int ooffset,
1316 char ta[] = toCharArray();
1317 int to = offset() + toffset;
1318 char pa[] = other.toCharArray();
1319 int po = other.offset() + ooffset;
1320 // Note: toffset, ooffset, or len might be near -1>>>1.
1321 if ((ooffset < 0) || (toffset < 0) || (toffset > (long)length() - len)
1322 || (ooffset > (long)other.length() - len)) {
1326 if (ta[to++] != pa[po++]) {
1334 * Tests if two string regions are equal.
1336 * A substring of this <tt>String</tt> object is compared to a substring
1337 * of the argument <tt>other</tt>. The result is <tt>true</tt> if these
1338 * substrings represent character sequences that are the same, ignoring
1339 * case if and only if <tt>ignoreCase</tt> is true. The substring of
1340 * this <tt>String</tt> object to be compared begins at index
1341 * <tt>toffset</tt> and has length <tt>len</tt>. The substring of
1342 * <tt>other</tt> to be compared begins at index <tt>ooffset</tt> and
1343 * has length <tt>len</tt>. The result is <tt>false</tt> if and only if
1344 * at least one of the following is true:
1345 * <ul><li><tt>toffset</tt> is negative.
1346 * <li><tt>ooffset</tt> is negative.
1347 * <li><tt>toffset+len</tt> is greater than the length of this
1348 * <tt>String</tt> object.
1349 * <li><tt>ooffset+len</tt> is greater than the length of the other
1351 * <li><tt>ignoreCase</tt> is <tt>false</tt> and there is some nonnegative
1352 * integer <i>k</i> less than <tt>len</tt> such that:
1354 * this.charAt(toffset+k) != other.charAt(ooffset+k)
1355 * </pre></blockquote>
1356 * <li><tt>ignoreCase</tt> is <tt>true</tt> and there is some nonnegative
1357 * integer <i>k</i> less than <tt>len</tt> such that:
1359 * Character.toLowerCase(this.charAt(toffset+k)) !=
1360 Character.toLowerCase(other.charAt(ooffset+k))
1361 * </pre></blockquote>
1364 * Character.toUpperCase(this.charAt(toffset+k)) !=
1365 * Character.toUpperCase(other.charAt(ooffset+k))
1366 * </pre></blockquote>
1369 * @param ignoreCase if <code>true</code>, ignore case when comparing
1371 * @param toffset the starting offset of the subregion in this
1373 * @param other the string argument.
1374 * @param ooffset the starting offset of the subregion in the string
1376 * @param len the number of characters to compare.
1377 * @return <code>true</code> if the specified subregion of this string
1378 * matches the specified subregion of the string argument;
1379 * <code>false</code> otherwise. Whether the matching is exact
1380 * or case insensitive depends on the <code>ignoreCase</code>
1383 public boolean regionMatches(boolean ignoreCase, int toffset,
1384 String other, int ooffset, int len) {
1385 char ta[] = toCharArray();
1386 int to = offset() + toffset;
1387 char pa[] = other.toCharArray();
1388 int po = other.offset() + ooffset;
1389 // Note: toffset, ooffset, or len might be near -1>>>1.
1390 if ((ooffset < 0) || (toffset < 0) || (toffset > (long)length() - len) ||
1391 (ooffset > (long)other.length() - len)) {
1401 // If characters don't match but case may be ignored,
1402 // try converting both characters to uppercase.
1403 // If the results match, then the comparison scan should
1405 char u1 = Character.toUpperCase(c1);
1406 char u2 = Character.toUpperCase(c2);
1410 // Unfortunately, conversion to uppercase does not work properly
1411 // for the Georgian alphabet, which has strange rules about case
1412 // conversion. So we need to make one last check before
1414 if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) {
1424 * Tests if the substring of this string beginning at the
1425 * specified index starts with the specified prefix.
1427 * @param prefix the prefix.
1428 * @param toffset where to begin looking in this string.
1429 * @return <code>true</code> if the character sequence represented by the
1430 * argument is a prefix of the substring of this object starting
1431 * at index <code>toffset</code>; <code>false</code> otherwise.
1432 * The result is <code>false</code> if <code>toffset</code> is
1433 * negative or greater than the length of this
1434 * <code>String</code> object; otherwise the result is the same
1435 * as the result of the expression
1437 * this.substring(toffset).startsWith(prefix)
1440 @JavaScriptBody(args = { "find", "from" }, body=
1441 "find = find.toString();\n" +
1442 "return this.toString().substring(from, from + find.length) === find;\n"
1444 public boolean startsWith(String prefix, int toffset) {
1445 char ta[] = toCharArray();
1446 int to = offset() + toffset;
1447 char pa[] = prefix.toCharArray();
1448 int po = prefix.offset();
1449 int pc = prefix.length();
1450 // Note: toffset might be near -1>>>1.
1451 if ((toffset < 0) || (toffset > length() - pc)) {
1455 if (ta[to++] != pa[po++]) {
1463 * Tests if this string starts with the specified prefix.
1465 * @param prefix the prefix.
1466 * @return <code>true</code> if the character sequence represented by the
1467 * argument is a prefix of the character sequence represented by
1468 * this string; <code>false</code> otherwise.
1469 * Note also that <code>true</code> will be returned if the
1470 * argument is an empty string or is equal to this
1471 * <code>String</code> object as determined by the
1472 * {@link #equals(Object)} method.
1475 public boolean startsWith(String prefix) {
1476 return startsWith(prefix, 0);
1480 * Tests if this string ends with the specified suffix.
1482 * @param suffix the suffix.
1483 * @return <code>true</code> if the character sequence represented by the
1484 * argument is a suffix of the character sequence represented by
1485 * this object; <code>false</code> otherwise. Note that the
1486 * result will be <code>true</code> if the argument is the
1487 * empty string or is equal to this <code>String</code> object
1488 * as determined by the {@link #equals(Object)} method.
1490 public boolean endsWith(String suffix) {
1491 return startsWith(suffix, length() - suffix.length());
1495 * Returns a hash code for this string. The hash code for a
1496 * <code>String</code> object is computed as
1498 * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
1499 * </pre></blockquote>
1500 * using <code>int</code> arithmetic, where <code>s[i]</code> is the
1501 * <i>i</i>th character of the string, <code>n</code> is the length of
1502 * the string, and <code>^</code> indicates exponentiation.
1503 * (The hash value of the empty string is zero.)
1505 * @return a hash code value for this object.
1507 public int hashCode() {
1508 return super.hashCode();
1510 int computeHashCode() {
1512 if (h == 0 && length() > 0) {
1516 for (int i = 0; i < len; i++) {
1517 h = 31*h + charAt(off++);
1524 * Returns the index within this string of the first occurrence of
1525 * the specified character. If a character with value
1526 * <code>ch</code> occurs in the character sequence represented by
1527 * this <code>String</code> object, then the index (in Unicode
1528 * code units) of the first such occurrence is returned. For
1529 * values of <code>ch</code> in the range from 0 to 0xFFFF
1530 * (inclusive), this is the smallest value <i>k</i> such that:
1532 * this.charAt(<i>k</i>) == ch
1533 * </pre></blockquote>
1534 * is true. For other values of <code>ch</code>, it is the
1535 * smallest value <i>k</i> such that:
1537 * this.codePointAt(<i>k</i>) == ch
1538 * </pre></blockquote>
1539 * is true. In either case, if no such character occurs in this
1540 * string, then <code>-1</code> is returned.
1542 * @param ch a character (Unicode code point).
1543 * @return the index of the first occurrence of the character in the
1544 * character sequence represented by this object, or
1545 * <code>-1</code> if the character does not occur.
1547 public int indexOf(int ch) {
1548 return indexOf(ch, 0);
1552 * Returns the index within this string of the first occurrence of the
1553 * specified character, starting the search at the specified index.
1555 * If a character with value <code>ch</code> occurs in the
1556 * character sequence represented by this <code>String</code>
1557 * object at an index no smaller than <code>fromIndex</code>, then
1558 * the index of the first such occurrence is returned. For values
1559 * of <code>ch</code> in the range from 0 to 0xFFFF (inclusive),
1560 * this is the smallest value <i>k</i> such that:
1562 * (this.charAt(<i>k</i>) == ch) && (<i>k</i> >= fromIndex)
1563 * </pre></blockquote>
1564 * is true. For other values of <code>ch</code>, it is the
1565 * smallest value <i>k</i> such that:
1567 * (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> >= fromIndex)
1568 * </pre></blockquote>
1569 * is true. In either case, if no such character occurs in this
1570 * string at or after position <code>fromIndex</code>, then
1571 * <code>-1</code> is returned.
1574 * There is no restriction on the value of <code>fromIndex</code>. If it
1575 * is negative, it has the same effect as if it were zero: this entire
1576 * string may be searched. If it is greater than the length of this
1577 * string, it has the same effect as if it were equal to the length of
1578 * this string: <code>-1</code> is returned.
1580 * <p>All indices are specified in <code>char</code> values
1581 * (Unicode code units).
1583 * @param ch a character (Unicode code point).
1584 * @param fromIndex the index to start the search from.
1585 * @return the index of the first occurrence of the character in the
1586 * character sequence represented by this object that is greater
1587 * than or equal to <code>fromIndex</code>, or <code>-1</code>
1588 * if the character does not occur.
1590 @JavaScriptBody(args = { "ch", "from" }, body =
1591 "if (typeof ch === 'number') ch = String.fromCharCode(ch);\n" +
1592 "return this.toString().indexOf(ch, from);\n"
1594 public int indexOf(int ch, int fromIndex) {
1595 if (fromIndex < 0) {
1597 } else if (fromIndex >= length()) {
1598 // Note: fromIndex might be near -1>>>1.
1602 if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
1603 // handle most cases here (ch is a BMP code point or a
1604 // negative value (invalid code point))
1605 final char[] value = this.toCharArray();
1606 final int offset = this.offset();
1607 final int max = offset + length();
1608 for (int i = offset + fromIndex; i < max ; i++) {
1609 if (value[i] == ch) {
1615 return indexOfSupplementary(ch, fromIndex);
1620 * Handles (rare) calls of indexOf with a supplementary character.
1622 private int indexOfSupplementary(int ch, int fromIndex) {
1623 if (Character.isValidCodePoint(ch)) {
1624 final char[] value = this.toCharArray();
1625 final int offset = this.offset();
1626 final char hi = Character.highSurrogate(ch);
1627 final char lo = Character.lowSurrogate(ch);
1628 final int max = offset + length() - 1;
1629 for (int i = offset + fromIndex; i < max; i++) {
1630 if (value[i] == hi && value[i+1] == lo) {
1639 * Returns the index within this string of the last occurrence of
1640 * the specified character. For values of <code>ch</code> in the
1641 * range from 0 to 0xFFFF (inclusive), the index (in Unicode code
1642 * units) returned is the largest value <i>k</i> such that:
1644 * this.charAt(<i>k</i>) == ch
1645 * </pre></blockquote>
1646 * is true. For other values of <code>ch</code>, it is the
1647 * largest value <i>k</i> such that:
1649 * this.codePointAt(<i>k</i>) == ch
1650 * </pre></blockquote>
1651 * is true. In either case, if no such character occurs in this
1652 * string, then <code>-1</code> is returned. The
1653 * <code>String</code> is searched backwards starting at the last
1656 * @param ch a character (Unicode code point).
1657 * @return the index of the last occurrence of the character in the
1658 * character sequence represented by this object, or
1659 * <code>-1</code> if the character does not occur.
1661 public int lastIndexOf(int ch) {
1662 return lastIndexOf(ch, length() - 1);
1666 * Returns the index within this string of the last occurrence of
1667 * the specified character, searching backward starting at the
1668 * specified index. For values of <code>ch</code> in the range
1669 * from 0 to 0xFFFF (inclusive), the index returned is the largest
1670 * value <i>k</i> such that:
1672 * (this.charAt(<i>k</i>) == ch) && (<i>k</i> <= fromIndex)
1673 * </pre></blockquote>
1674 * is true. For other values of <code>ch</code>, it is the
1675 * largest value <i>k</i> such that:
1677 * (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> <= fromIndex)
1678 * </pre></blockquote>
1679 * is true. In either case, if no such character occurs in this
1680 * string at or before position <code>fromIndex</code>, then
1681 * <code>-1</code> is returned.
1683 * <p>All indices are specified in <code>char</code> values
1684 * (Unicode code units).
1686 * @param ch a character (Unicode code point).
1687 * @param fromIndex the index to start the search from. There is no
1688 * restriction on the value of <code>fromIndex</code>. If it is
1689 * greater than or equal to the length of this string, it has
1690 * the same effect as if it were equal to one less than the
1691 * length of this string: this entire string may be searched.
1692 * If it is negative, it has the same effect as if it were -1:
1694 * @return the index of the last occurrence of the character in the
1695 * character sequence represented by this object that is less
1696 * than or equal to <code>fromIndex</code>, or <code>-1</code>
1697 * if the character does not occur before that point.
1699 @JavaScriptBody(args = { "ch", "from" }, body =
1700 "if (typeof ch === 'number') ch = String.fromCharCode(ch);\n" +
1701 "return this.toString().lastIndexOf(ch, from);"
1703 public int lastIndexOf(int ch, int fromIndex) {
1704 if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
1705 // handle most cases here (ch is a BMP code point or a
1706 // negative value (invalid code point))
1707 final char[] value = this.toCharArray();
1708 final int offset = this.offset();
1709 int i = offset + Math.min(fromIndex, length() - 1);
1710 for (; i >= offset ; i--) {
1711 if (value[i] == ch) {
1717 return lastIndexOfSupplementary(ch, fromIndex);
1722 * Handles (rare) calls of lastIndexOf with a supplementary character.
1724 private int lastIndexOfSupplementary(int ch, int fromIndex) {
1725 if (Character.isValidCodePoint(ch)) {
1726 final char[] value = this.toCharArray();
1727 final int offset = this.offset();
1728 char hi = Character.highSurrogate(ch);
1729 char lo = Character.lowSurrogate(ch);
1730 int i = offset + Math.min(fromIndex, length() - 2);
1731 for (; i >= offset; i--) {
1732 if (value[i] == hi && value[i+1] == lo) {
1741 * Returns the index within this string of the first occurrence of the
1742 * specified substring.
1744 * <p>The returned index is the smallest value <i>k</i> for which:
1746 * this.startsWith(str, <i>k</i>)
1747 * </pre></blockquote>
1748 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1750 * @param str the substring to search for.
1751 * @return the index of the first occurrence of the specified substring,
1752 * or {@code -1} if there is no such occurrence.
1754 public int indexOf(String str) {
1755 return indexOf(str, 0);
1759 * Returns the index within this string of the first occurrence of the
1760 * specified substring, starting at the specified index.
1762 * <p>The returned index is the smallest value <i>k</i> for which:
1764 * <i>k</i> >= fromIndex && this.startsWith(str, <i>k</i>)
1765 * </pre></blockquote>
1766 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1768 * @param str the substring to search for.
1769 * @param fromIndex the index from which to start the search.
1770 * @return the index of the first occurrence of the specified substring,
1771 * starting at the specified index,
1772 * or {@code -1} if there is no such occurrence.
1774 @JavaScriptBody(args = { "str", "fromIndex" }, body =
1775 "return this.toString().indexOf(str.toString(), fromIndex);"
1777 public native int indexOf(String str, int fromIndex);
1780 * Returns the index within this string of the last occurrence of the
1781 * specified substring. The last occurrence of the empty string ""
1782 * is considered to occur at the index value {@code this.length()}.
1784 * <p>The returned index is the largest value <i>k</i> for which:
1786 * this.startsWith(str, <i>k</i>)
1787 * </pre></blockquote>
1788 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1790 * @param str the substring to search for.
1791 * @return the index of the last occurrence of the specified substring,
1792 * or {@code -1} if there is no such occurrence.
1794 public int lastIndexOf(String str) {
1795 return lastIndexOf(str, length());
1799 * Returns the index within this string of the last occurrence of the
1800 * specified substring, searching backward starting at the specified index.
1802 * <p>The returned index is the largest value <i>k</i> for which:
1804 * <i>k</i> <= fromIndex && this.startsWith(str, <i>k</i>)
1805 * </pre></blockquote>
1806 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1808 * @param str the substring to search for.
1809 * @param fromIndex the index to start the search from.
1810 * @return the index of the last occurrence of the specified substring,
1811 * searching backward from the specified index,
1812 * or {@code -1} if there is no such occurrence.
1814 @JavaScriptBody(args = { "s", "from" }, body =
1815 "return this.toString().lastIndexOf(s.toString(), from);"
1817 public int lastIndexOf(String str, int fromIndex) {
1818 return lastIndexOf(toCharArray(), offset(), length(), str.toCharArray(), str.offset(), str.length(), fromIndex);
1822 * Code shared by String and StringBuffer to do searches. The
1823 * source is the character array being searched, and the target
1824 * is the string being searched for.
1826 * @param source the characters being searched.
1827 * @param sourceOffset offset of the source string.
1828 * @param sourceCount count of the source string.
1829 * @param target the characters being searched for.
1830 * @param targetOffset offset of the target string.
1831 * @param targetCount count of the target string.
1832 * @param fromIndex the index to begin searching from.
1834 static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
1835 char[] target, int targetOffset, int targetCount,
1838 * Check arguments; return immediately where possible. For
1839 * consistency, don't check for null str.
1841 int rightIndex = sourceCount - targetCount;
1842 if (fromIndex < 0) {
1845 if (fromIndex > rightIndex) {
1846 fromIndex = rightIndex;
1848 /* Empty string always matches. */
1849 if (targetCount == 0) {
1853 int strLastIndex = targetOffset + targetCount - 1;
1854 char strLastChar = target[strLastIndex];
1855 int min = sourceOffset + targetCount - 1;
1856 int i = min + fromIndex;
1858 startSearchForLastChar:
1860 while (i >= min && source[i] != strLastChar) {
1867 int start = j - (targetCount - 1);
1868 int k = strLastIndex - 1;
1871 if (source[j--] != target[k--]) {
1873 continue startSearchForLastChar;
1876 return start - sourceOffset + 1;
1881 * Returns a new string that is a substring of this string. The
1882 * substring begins with the character at the specified index and
1883 * extends to the end of this string. <p>
1886 * "unhappy".substring(2) returns "happy"
1887 * "Harbison".substring(3) returns "bison"
1888 * "emptiness".substring(9) returns "" (an empty string)
1889 * </pre></blockquote>
1891 * @param beginIndex the beginning index, inclusive.
1892 * @return the specified substring.
1893 * @exception IndexOutOfBoundsException if
1894 * <code>beginIndex</code> is negative or larger than the
1895 * length of this <code>String</code> object.
1897 public String substring(int beginIndex) {
1898 return substring(beginIndex, length());
1902 * Returns a new string that is a substring of this string. The
1903 * substring begins at the specified <code>beginIndex</code> and
1904 * extends to the character at index <code>endIndex - 1</code>.
1905 * Thus the length of the substring is <code>endIndex-beginIndex</code>.
1909 * "hamburger".substring(4, 8) returns "urge"
1910 * "smiles".substring(1, 5) returns "mile"
1911 * </pre></blockquote>
1913 * @param beginIndex the beginning index, inclusive.
1914 * @param endIndex the ending index, exclusive.
1915 * @return the specified substring.
1916 * @exception IndexOutOfBoundsException if the
1917 * <code>beginIndex</code> is negative, or
1918 * <code>endIndex</code> is larger than the length of
1919 * this <code>String</code> object, or
1920 * <code>beginIndex</code> is larger than
1921 * <code>endIndex</code>.
1923 @JavaScriptBody(args = { "beginIndex", "endIndex" }, body =
1924 "return this.toString().substring(beginIndex, endIndex);"
1926 public String substring(int beginIndex, int endIndex) {
1927 if (beginIndex < 0) {
1928 throw new StringIndexOutOfBoundsException(beginIndex);
1930 if (endIndex > length()) {
1931 throw new StringIndexOutOfBoundsException(endIndex);
1933 if (beginIndex > endIndex) {
1934 throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
1936 return ((beginIndex == 0) && (endIndex == length())) ? this :
1937 new String(toCharArray(), offset() + beginIndex, endIndex - beginIndex);
1941 * Returns a new character sequence that is a subsequence of this sequence.
1943 * <p> An invocation of this method of the form
1946 * str.subSequence(begin, end)</pre></blockquote>
1948 * behaves in exactly the same way as the invocation
1951 * str.substring(begin, end)</pre></blockquote>
1953 * This method is defined so that the <tt>String</tt> class can implement
1954 * the {@link CharSequence} interface. </p>
1956 * @param beginIndex the begin index, inclusive.
1957 * @param endIndex the end index, exclusive.
1958 * @return the specified subsequence.
1960 * @throws IndexOutOfBoundsException
1961 * if <tt>beginIndex</tt> or <tt>endIndex</tt> are negative,
1962 * if <tt>endIndex</tt> is greater than <tt>length()</tt>,
1963 * or if <tt>beginIndex</tt> is greater than <tt>startIndex</tt>
1968 public CharSequence subSequence(int beginIndex, int endIndex) {
1969 return this.substring(beginIndex, endIndex);
1973 * Concatenates the specified string to the end of this string.
1975 * If the length of the argument string is <code>0</code>, then this
1976 * <code>String</code> object is returned. Otherwise, a new
1977 * <code>String</code> object is created, representing a character
1978 * sequence that is the concatenation of the character sequence
1979 * represented by this <code>String</code> object and the character
1980 * sequence represented by the argument string.<p>
1983 * "cares".concat("s") returns "caress"
1984 * "to".concat("get").concat("her") returns "together"
1985 * </pre></blockquote>
1987 * @param str the <code>String</code> that is concatenated to the end
1988 * of this <code>String</code>.
1989 * @return a string that represents the concatenation of this object's
1990 * characters followed by the string argument's characters.
1992 public String concat(String str) {
1993 int otherLen = str.length();
1994 if (otherLen == 0) {
1997 char buf[] = new char[length() + otherLen];
1998 getChars(0, length(), buf, 0);
1999 str.getChars(0, otherLen, buf, length());
2000 return new String(buf, 0, length() + otherLen);
2004 * Returns a new string resulting from replacing all occurrences of
2005 * <code>oldChar</code> in this string with <code>newChar</code>.
2007 * If the character <code>oldChar</code> does not occur in the
2008 * character sequence represented by this <code>String</code> object,
2009 * then a reference to this <code>String</code> object is returned.
2010 * Otherwise, a new <code>String</code> object is created that
2011 * represents a character sequence identical to the character sequence
2012 * represented by this <code>String</code> object, except that every
2013 * occurrence of <code>oldChar</code> is replaced by an occurrence
2014 * of <code>newChar</code>.
2018 * "mesquite in your cellar".replace('e', 'o')
2019 * returns "mosquito in your collar"
2020 * "the war of baronets".replace('r', 'y')
2021 * returns "the way of bayonets"
2022 * "sparring with a purple porpoise".replace('p', 't')
2023 * returns "starring with a turtle tortoise"
2024 * "JonL".replace('q', 'x') returns "JonL" (no change)
2025 * </pre></blockquote>
2027 * @param oldChar the old character.
2028 * @param newChar the new character.
2029 * @return a string derived from this string by replacing every
2030 * occurrence of <code>oldChar</code> with <code>newChar</code>.
2032 @JavaScriptBody(args = { "arg1", "arg2" }, body =
2033 "if (typeof arg1 === 'number') arg1 = String.fromCharCode(arg1);\n" +
2034 "if (typeof arg2 === 'number') arg2 = String.fromCharCode(arg2);\n" +
2035 "var s = this.toString();\n" +
2037 " var ret = s.replace(arg1, arg2);\n" +
2038 " if (ret === s) {\n" +
2044 public String replace(char oldChar, char newChar) {
2045 if (oldChar != newChar) {
2048 char[] val = toCharArray(); /* avoid getfield opcode */
2049 int off = offset(); /* avoid getfield opcode */
2052 if (val[off + i] == oldChar) {
2057 char buf[] = new char[len];
2058 for (int j = 0 ; j < i ; j++) {
2059 buf[j] = val[off+j];
2062 char c = val[off + i];
2063 buf[i] = (c == oldChar) ? newChar : c;
2066 return new String(buf, 0, len);
2073 * Tells whether or not this string matches the given <a
2074 * href="../util/regex/Pattern.html#sum">regular expression</a>.
2076 * <p> An invocation of this method of the form
2077 * <i>str</i><tt>.matches(</tt><i>regex</i><tt>)</tt> yields exactly the
2078 * same result as the expression
2080 * <blockquote><tt> {@link java.util.regex.Pattern}.{@link
2081 * java.util.regex.Pattern#matches(String,CharSequence)
2082 * matches}(</tt><i>regex</i><tt>,</tt> <i>str</i><tt>)</tt></blockquote>
2085 * the regular expression to which this string is to be matched
2087 * @return <tt>true</tt> if, and only if, this string matches the
2088 * given regular expression
2090 * @throws PatternSyntaxException
2091 * if the regular expression's syntax is invalid
2093 * @see java.util.regex.Pattern
2098 @JavaScriptBody(args = { "regex" }, body =
2099 "var self = this.toString();\n"
2100 + "var re = new RegExp(regex.toString());\n"
2101 + "var r = re.exec(self);\n"
2102 + "return r != null && r.length > 0 && self.length == r[0].length;"
2104 public boolean matches(String regex) {
2105 throw new UnsupportedOperationException();
2109 * Returns true if and only if this string contains the specified
2110 * sequence of char values.
2112 * @param s the sequence to search for
2113 * @return true if this string contains <code>s</code>, false otherwise
2114 * @throws NullPointerException if <code>s</code> is <code>null</code>
2117 public boolean contains(CharSequence s) {
2118 return indexOf(s.toString()) > -1;
2122 * Replaces the first substring of this string that matches the given <a
2123 * href="../util/regex/Pattern.html#sum">regular expression</a> with the
2124 * given replacement.
2126 * <p> An invocation of this method of the form
2127 * <i>str</i><tt>.replaceFirst(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt>
2128 * yields exactly the same result as the expression
2131 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2132 * compile}(</tt><i>regex</i><tt>).{@link
2133 * java.util.regex.Pattern#matcher(java.lang.CharSequence)
2134 * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceFirst
2135 * replaceFirst}(</tt><i>repl</i><tt>)</tt></blockquote>
2138 * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the
2139 * replacement string may cause the results to be different than if it were
2140 * being treated as a literal replacement string; see
2141 * {@link java.util.regex.Matcher#replaceFirst}.
2142 * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
2143 * meaning of these characters, if desired.
2146 * the regular expression to which this string is to be matched
2147 * @param replacement
2148 * the string to be substituted for the first match
2150 * @return The resulting <tt>String</tt>
2152 * @throws PatternSyntaxException
2153 * if the regular expression's syntax is invalid
2155 * @see java.util.regex.Pattern
2160 public String replaceFirst(String regex, String replacement) {
2161 throw new UnsupportedOperationException();
2165 * Replaces each substring of this string that matches the given <a
2166 * href="../util/regex/Pattern.html#sum">regular expression</a> with the
2167 * given replacement.
2169 * <p> An invocation of this method of the form
2170 * <i>str</i><tt>.replaceAll(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt>
2171 * yields exactly the same result as the expression
2174 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2175 * compile}(</tt><i>regex</i><tt>).{@link
2176 * java.util.regex.Pattern#matcher(java.lang.CharSequence)
2177 * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceAll
2178 * replaceAll}(</tt><i>repl</i><tt>)</tt></blockquote>
2181 * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the
2182 * replacement string may cause the results to be different than if it were
2183 * being treated as a literal replacement string; see
2184 * {@link java.util.regex.Matcher#replaceAll Matcher.replaceAll}.
2185 * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
2186 * meaning of these characters, if desired.
2189 * the regular expression to which this string is to be matched
2190 * @param replacement
2191 * the string to be substituted for each match
2193 * @return The resulting <tt>String</tt>
2195 * @throws PatternSyntaxException
2196 * if the regular expression's syntax is invalid
2198 * @see java.util.regex.Pattern
2203 public String replaceAll(String regex, String replacement) {
2204 throw new UnsupportedOperationException();
2208 * Replaces each substring of this string that matches the literal target
2209 * sequence with the specified literal replacement sequence. The
2210 * replacement proceeds from the beginning of the string to the end, for
2211 * example, replacing "aa" with "b" in the string "aaa" will result in
2212 * "ba" rather than "ab".
2214 * @param target The sequence of char values to be replaced
2215 * @param replacement The replacement sequence of char values
2216 * @return The resulting string
2217 * @throws NullPointerException if <code>target</code> or
2218 * <code>replacement</code> is <code>null</code>.
2221 public String replace(CharSequence target, CharSequence replacement) {
2222 throw new UnsupportedOperationException("This one should be supported, but without dep on rest of regexp");
2226 * Splits this string around matches of the given
2227 * <a href="../util/regex/Pattern.html#sum">regular expression</a>.
2229 * <p> The array returned by this method contains each substring of this
2230 * string that is terminated by another substring that matches the given
2231 * expression or is terminated by the end of the string. The substrings in
2232 * the array are in the order in which they occur in this string. If the
2233 * expression does not match any part of the input then the resulting array
2234 * has just one element, namely this string.
2236 * <p> The <tt>limit</tt> parameter controls the number of times the
2237 * pattern is applied and therefore affects the length of the resulting
2238 * array. If the limit <i>n</i> is greater than zero then the pattern
2239 * will be applied at most <i>n</i> - 1 times, the array's
2240 * length will be no greater than <i>n</i>, and the array's last entry
2241 * will contain all input beyond the last matched delimiter. If <i>n</i>
2242 * is non-positive then the pattern will be applied as many times as
2243 * possible and the array can have any length. If <i>n</i> is zero then
2244 * the pattern will be applied as many times as possible, the array can
2245 * have any length, and trailing empty strings will be discarded.
2247 * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the
2248 * following results with these parameters:
2250 * <blockquote><table cellpadding=1 cellspacing=0 summary="Split example showing regex, limit, and result">
2256 * <tr><td align=center>:</td>
2257 * <td align=center>2</td>
2258 * <td><tt>{ "boo", "and:foo" }</tt></td></tr>
2259 * <tr><td align=center>:</td>
2260 * <td align=center>5</td>
2261 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2262 * <tr><td align=center>:</td>
2263 * <td align=center>-2</td>
2264 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2265 * <tr><td align=center>o</td>
2266 * <td align=center>5</td>
2267 * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
2268 * <tr><td align=center>o</td>
2269 * <td align=center>-2</td>
2270 * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
2271 * <tr><td align=center>o</td>
2272 * <td align=center>0</td>
2273 * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
2274 * </table></blockquote>
2276 * <p> An invocation of this method of the form
2277 * <i>str.</i><tt>split(</tt><i>regex</i><tt>,</tt> <i>n</i><tt>)</tt>
2278 * yields the same result as the expression
2281 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2282 * compile}<tt>(</tt><i>regex</i><tt>)</tt>.{@link
2283 * java.util.regex.Pattern#split(java.lang.CharSequence,int)
2284 * split}<tt>(</tt><i>str</i><tt>,</tt> <i>n</i><tt>)</tt>
2289 * the delimiting regular expression
2292 * the result threshold, as described above
2294 * @return the array of strings computed by splitting this string
2295 * around matches of the given regular expression
2297 * @throws PatternSyntaxException
2298 * if the regular expression's syntax is invalid
2300 * @see java.util.regex.Pattern
2305 public String[] split(String regex, int limit) {
2306 throw new UnsupportedOperationException("Needs regexp");
2310 * Splits this string around matches of the given <a
2311 * href="../util/regex/Pattern.html#sum">regular expression</a>.
2313 * <p> This method works as if by invoking the two-argument {@link
2314 * #split(String, int) split} method with the given expression and a limit
2315 * argument of zero. Trailing empty strings are therefore not included in
2316 * the resulting array.
2318 * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the following
2319 * results with these expressions:
2321 * <blockquote><table cellpadding=1 cellspacing=0 summary="Split examples showing regex and result">
2326 * <tr><td align=center>:</td>
2327 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2328 * <tr><td align=center>o</td>
2329 * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
2330 * </table></blockquote>
2334 * the delimiting regular expression
2336 * @return the array of strings computed by splitting this string
2337 * around matches of the given regular expression
2339 * @throws PatternSyntaxException
2340 * if the regular expression's syntax is invalid
2342 * @see java.util.regex.Pattern
2347 public String[] split(String regex) {
2348 return split(regex, 0);
2352 * Converts all of the characters in this <code>String</code> to lower
2353 * case using the rules of the given <code>Locale</code>. Case mapping is based
2354 * on the Unicode Standard version specified by the {@link java.lang.Character Character}
2355 * class. Since case mappings are not always 1:1 char mappings, the resulting
2356 * <code>String</code> may be a different length than the original <code>String</code>.
2358 * Examples of lowercase mappings are in the following table:
2359 * <table border="1" summary="Lowercase mapping examples showing language code of locale, upper case, lower case, and description">
2361 * <th>Language Code of Locale</th>
2362 * <th>Upper Case</th>
2363 * <th>Lower Case</th>
2364 * <th>Description</th>
2367 * <td>tr (Turkish)</td>
2368 * <td>\u0130</td>
2369 * <td>\u0069</td>
2370 * <td>capital letter I with dot above -> small letter i</td>
2373 * <td>tr (Turkish)</td>
2374 * <td>\u0049</td>
2375 * <td>\u0131</td>
2376 * <td>capital letter I -> small letter dotless i </td>
2380 * <td>French Fries</td>
2381 * <td>french fries</td>
2382 * <td>lowercased all chars in String</td>
2386 * <td><img src="doc-files/capiota.gif" alt="capiota"><img src="doc-files/capchi.gif" alt="capchi">
2387 * <img src="doc-files/captheta.gif" alt="captheta"><img src="doc-files/capupsil.gif" alt="capupsil">
2388 * <img src="doc-files/capsigma.gif" alt="capsigma"></td>
2389 * <td><img src="doc-files/iota.gif" alt="iota"><img src="doc-files/chi.gif" alt="chi">
2390 * <img src="doc-files/theta.gif" alt="theta"><img src="doc-files/upsilon.gif" alt="upsilon">
2391 * <img src="doc-files/sigma1.gif" alt="sigma"></td>
2392 * <td>lowercased all chars in String</td>
2396 * @param locale use the case transformation rules for this locale
2397 * @return the <code>String</code>, converted to lowercase.
2398 * @see java.lang.String#toLowerCase()
2399 * @see java.lang.String#toUpperCase()
2400 * @see java.lang.String#toUpperCase(Locale)
2403 // public String toLowerCase(Locale locale) {
2404 // if (locale == null) {
2405 // throw new NullPointerException();
2410 // /* Now check if there are any characters that need to be changed. */
2412 // for (firstUpper = 0 ; firstUpper < count; ) {
2413 // char c = value[offset+firstUpper];
2414 // if ((c >= Character.MIN_HIGH_SURROGATE) &&
2415 // (c <= Character.MAX_HIGH_SURROGATE)) {
2416 // int supplChar = codePointAt(firstUpper);
2417 // if (supplChar != Character.toLowerCase(supplChar)) {
2420 // firstUpper += Character.charCount(supplChar);
2422 // if (c != Character.toLowerCase(c)) {
2431 // char[] result = new char[count];
2432 // int resultOffset = 0; /* result may grow, so i+resultOffset
2433 // * is the write location in result */
2435 // /* Just copy the first few lowerCase characters. */
2436 // System.arraycopy(value, offset, result, 0, firstUpper);
2438 // String lang = locale.getLanguage();
2439 // boolean localeDependent =
2440 // (lang == "tr" || lang == "az" || lang == "lt");
2441 // char[] lowerCharArray;
2445 // for (int i = firstUpper; i < count; i += srcCount) {
2446 // srcChar = (int)value[offset+i];
2447 // if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
2448 // (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
2449 // srcChar = codePointAt(i);
2450 // srcCount = Character.charCount(srcChar);
2454 // if (localeDependent || srcChar == '\u03A3') { // GREEK CAPITAL LETTER SIGMA
2455 // lowerChar = ConditionalSpecialCasing.toLowerCaseEx(this, i, locale);
2456 // } else if (srcChar == '\u0130') { // LATIN CAPITAL LETTER I DOT
2457 // lowerChar = Character.ERROR;
2459 // lowerChar = Character.toLowerCase(srcChar);
2461 // if ((lowerChar == Character.ERROR) ||
2462 // (lowerChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
2463 // if (lowerChar == Character.ERROR) {
2464 // if (!localeDependent && srcChar == '\u0130') {
2466 // ConditionalSpecialCasing.toLowerCaseCharArray(this, i, Locale.ENGLISH);
2469 // ConditionalSpecialCasing.toLowerCaseCharArray(this, i, locale);
2471 // } else if (srcCount == 2) {
2472 // resultOffset += Character.toChars(lowerChar, result, i + resultOffset) - srcCount;
2475 // lowerCharArray = Character.toChars(lowerChar);
2478 // /* Grow result if needed */
2479 // int mapLen = lowerCharArray.length;
2480 // if (mapLen > srcCount) {
2481 // char[] result2 = new char[result.length + mapLen - srcCount];
2482 // System.arraycopy(result, 0, result2, 0,
2483 // i + resultOffset);
2484 // result = result2;
2486 // for (int x=0; x<mapLen; ++x) {
2487 // result[i+resultOffset+x] = lowerCharArray[x];
2489 // resultOffset += (mapLen - srcCount);
2491 // result[i+resultOffset] = (char)lowerChar;
2494 // return new String(0, count+resultOffset, result);
2498 * Converts all of the characters in this <code>String</code> to lower
2499 * case using the rules of the default locale. This is equivalent to calling
2500 * <code>toLowerCase(Locale.getDefault())</code>.
2502 * <b>Note:</b> This method is locale sensitive, and may produce unexpected
2503 * results if used for strings that are intended to be interpreted locale
2505 * Examples are programming language identifiers, protocol keys, and HTML
2507 * For instance, <code>"TITLE".toLowerCase()</code> in a Turkish locale
2508 * returns <code>"t\u005Cu0131tle"</code>, where '\u005Cu0131' is the
2509 * LATIN SMALL LETTER DOTLESS I character.
2510 * To obtain correct results for locale insensitive strings, use
2511 * <code>toLowerCase(Locale.ENGLISH)</code>.
2513 * @return the <code>String</code>, converted to lowercase.
2514 * @see java.lang.String#toLowerCase(Locale)
2516 @JavaScriptBody(args = {}, body = "return this.toLowerCase();")
2517 public String toLowerCase() {
2518 throw new UnsupportedOperationException("Should be supported but without connection to locale");
2522 * Converts all of the characters in this <code>String</code> to upper
2523 * case using the rules of the given <code>Locale</code>. Case mapping is based
2524 * on the Unicode Standard version specified by the {@link java.lang.Character Character}
2525 * class. Since case mappings are not always 1:1 char mappings, the resulting
2526 * <code>String</code> may be a different length than the original <code>String</code>.
2528 * Examples of locale-sensitive and 1:M case mappings are in the following table.
2530 * <table border="1" summary="Examples of locale-sensitive and 1:M case mappings. Shows Language code of locale, lower case, upper case, and description.">
2532 * <th>Language Code of Locale</th>
2533 * <th>Lower Case</th>
2534 * <th>Upper Case</th>
2535 * <th>Description</th>
2538 * <td>tr (Turkish)</td>
2539 * <td>\u0069</td>
2540 * <td>\u0130</td>
2541 * <td>small letter i -> capital letter I with dot above</td>
2544 * <td>tr (Turkish)</td>
2545 * <td>\u0131</td>
2546 * <td>\u0049</td>
2547 * <td>small letter dotless i -> capital letter I</td>
2551 * <td>\u00df</td>
2552 * <td>\u0053 \u0053</td>
2553 * <td>small letter sharp s -> two letters: SS</td>
2557 * <td>Fahrvergnügen</td>
2558 * <td>FAHRVERGNÜGEN</td>
2562 * @param locale use the case transformation rules for this locale
2563 * @return the <code>String</code>, converted to uppercase.
2564 * @see java.lang.String#toUpperCase()
2565 * @see java.lang.String#toLowerCase()
2566 * @see java.lang.String#toLowerCase(Locale)
2569 /* not for javascript
2570 public String toUpperCase(Locale locale) {
2571 if (locale == null) {
2572 throw new NullPointerException();
2577 // Now check if there are any characters that need to be changed.
2579 for (firstLower = 0 ; firstLower < count; ) {
2580 int c = (int)value[offset+firstLower];
2582 if ((c >= Character.MIN_HIGH_SURROGATE) &&
2583 (c <= Character.MAX_HIGH_SURROGATE)) {
2584 c = codePointAt(firstLower);
2585 srcCount = Character.charCount(c);
2589 int upperCaseChar = Character.toUpperCaseEx(c);
2590 if ((upperCaseChar == Character.ERROR) ||
2591 (c != upperCaseChar)) {
2594 firstLower += srcCount;
2599 char[] result = new char[count]; /* may grow *
2600 int resultOffset = 0; /* result may grow, so i+resultOffset
2601 * is the write location in result *
2603 /* Just copy the first few upperCase characters. *
2604 System.arraycopy(value, offset, result, 0, firstLower);
2606 String lang = locale.getLanguage();
2607 boolean localeDependent =
2608 (lang == "tr" || lang == "az" || lang == "lt");
2609 char[] upperCharArray;
2613 for (int i = firstLower; i < count; i += srcCount) {
2614 srcChar = (int)value[offset+i];
2615 if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
2616 (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
2617 srcChar = codePointAt(i);
2618 srcCount = Character.charCount(srcChar);
2622 if (localeDependent) {
2623 upperChar = ConditionalSpecialCasing.toUpperCaseEx(this, i, locale);
2625 upperChar = Character.toUpperCaseEx(srcChar);
2627 if ((upperChar == Character.ERROR) ||
2628 (upperChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
2629 if (upperChar == Character.ERROR) {
2630 if (localeDependent) {
2632 ConditionalSpecialCasing.toUpperCaseCharArray(this, i, locale);
2634 upperCharArray = Character.toUpperCaseCharArray(srcChar);
2636 } else if (srcCount == 2) {
2637 resultOffset += Character.toChars(upperChar, result, i + resultOffset) - srcCount;
2640 upperCharArray = Character.toChars(upperChar);
2643 /* Grow result if needed *
2644 int mapLen = upperCharArray.length;
2645 if (mapLen > srcCount) {
2646 char[] result2 = new char[result.length + mapLen - srcCount];
2647 System.arraycopy(result, 0, result2, 0,
2651 for (int x=0; x<mapLen; ++x) {
2652 result[i+resultOffset+x] = upperCharArray[x];
2654 resultOffset += (mapLen - srcCount);
2656 result[i+resultOffset] = (char)upperChar;
2659 return new String(0, count+resultOffset, result);
2664 * Converts all of the characters in this <code>String</code> to upper
2665 * case using the rules of the default locale. This method is equivalent to
2666 * <code>toUpperCase(Locale.getDefault())</code>.
2668 * <b>Note:</b> This method is locale sensitive, and may produce unexpected
2669 * results if used for strings that are intended to be interpreted locale
2671 * Examples are programming language identifiers, protocol keys, and HTML
2673 * For instance, <code>"title".toUpperCase()</code> in a Turkish locale
2674 * returns <code>"T\u005Cu0130TLE"</code>, where '\u005Cu0130' is the
2675 * LATIN CAPITAL LETTER I WITH DOT ABOVE character.
2676 * To obtain correct results for locale insensitive strings, use
2677 * <code>toUpperCase(Locale.ENGLISH)</code>.
2679 * @return the <code>String</code>, converted to uppercase.
2680 * @see java.lang.String#toUpperCase(Locale)
2682 @JavaScriptBody(args = {}, body = "return this.toUpperCase();")
2683 public String toUpperCase() {
2684 throw new UnsupportedOperationException();
2688 * Returns a copy of the string, with leading and trailing whitespace
2691 * If this <code>String</code> object represents an empty character
2692 * sequence, or the first and last characters of character sequence
2693 * represented by this <code>String</code> object both have codes
2694 * greater than <code>'\u0020'</code> (the space character), then a
2695 * reference to this <code>String</code> object is returned.
2697 * Otherwise, if there is no character with a code greater than
2698 * <code>'\u0020'</code> in the string, then a new
2699 * <code>String</code> object representing an empty string is created
2702 * Otherwise, let <i>k</i> be the index of the first character in the
2703 * string whose code is greater than <code>'\u0020'</code>, and let
2704 * <i>m</i> be the index of the last character in the string whose code
2705 * is greater than <code>'\u0020'</code>. A new <code>String</code>
2706 * object is created, representing the substring of this string that
2707 * begins with the character at index <i>k</i> and ends with the
2708 * character at index <i>m</i>-that is, the result of
2709 * <code>this.substring(<i>k</i>, <i>m</i>+1)</code>.
2711 * This method may be used to trim whitespace (as defined above) from
2712 * the beginning and end of a string.
2714 * @return A copy of this string with leading and trailing white
2715 * space removed, or this string if it has no leading or
2716 * trailing white space.
2718 public String trim() {
2721 int off = offset(); /* avoid getfield opcode */
2722 char[] val = toCharArray(); /* avoid getfield opcode */
2724 while ((st < len) && (val[off + st] <= ' ')) {
2727 while ((st < len) && (val[off + len - 1] <= ' ')) {
2730 return ((st > 0) || (len < length())) ? substring(st, len) : this;
2734 * This object (which is already a string!) is itself returned.
2736 * @return the string itself.
2738 @JavaScriptBody(args = {}, body = "return this.toString();")
2739 public String toString() {
2744 * Converts this string to a new character array.
2746 * @return a newly allocated character array whose length is the length
2747 * of this string and whose contents are initialized to contain
2748 * the character sequence represented by this string.
2750 public char[] toCharArray() {
2751 char result[] = new char[length()];
2752 getChars(0, length(), result, 0);
2757 * Returns a formatted string using the specified format string and
2760 * <p> The locale always used is the one returned by {@link
2761 * java.util.Locale#getDefault() Locale.getDefault()}.
2764 * A <a href="../util/Formatter.html#syntax">format string</a>
2767 * Arguments referenced by the format specifiers in the format
2768 * string. If there are more arguments than format specifiers, the
2769 * extra arguments are ignored. The number of arguments is
2770 * variable and may be zero. The maximum number of arguments is
2771 * limited by the maximum dimension of a Java array as defined by
2772 * <cite>The Java™ Virtual Machine Specification</cite>.
2773 * The behaviour on a
2774 * <tt>null</tt> argument depends on the <a
2775 * href="../util/Formatter.html#syntax">conversion</a>.
2777 * @throws IllegalFormatException
2778 * If a format string contains an illegal syntax, a format
2779 * specifier that is incompatible with the given arguments,
2780 * insufficient arguments given the format string, or other
2781 * illegal conditions. For specification of all possible
2782 * formatting errors, see the <a
2783 * href="../util/Formatter.html#detail">Details</a> section of the
2784 * formatter class specification.
2786 * @throws NullPointerException
2787 * If the <tt>format</tt> is <tt>null</tt>
2789 * @return A formatted string
2791 * @see java.util.Formatter
2794 public static String format(String format, Object ... args) {
2795 throw new UnsupportedOperationException();
2799 * Returns a formatted string using the specified locale, format string,
2803 * The {@linkplain java.util.Locale locale} to apply during
2804 * formatting. If <tt>l</tt> is <tt>null</tt> then no localization
2808 * A <a href="../util/Formatter.html#syntax">format string</a>
2811 * Arguments referenced by the format specifiers in the format
2812 * string. If there are more arguments than format specifiers, the
2813 * extra arguments are ignored. The number of arguments is
2814 * variable and may be zero. The maximum number of arguments is
2815 * limited by the maximum dimension of a Java array as defined by
2816 * <cite>The Java™ Virtual Machine Specification</cite>.
2817 * The behaviour on a
2818 * <tt>null</tt> argument depends on the <a
2819 * href="../util/Formatter.html#syntax">conversion</a>.
2821 * @throws IllegalFormatException
2822 * If a format string contains an illegal syntax, a format
2823 * specifier that is incompatible with the given arguments,
2824 * insufficient arguments given the format string, or other
2825 * illegal conditions. For specification of all possible
2826 * formatting errors, see the <a
2827 * href="../util/Formatter.html#detail">Details</a> section of the
2828 * formatter class specification
2830 * @throws NullPointerException
2831 * If the <tt>format</tt> is <tt>null</tt>
2833 * @return A formatted string
2835 * @see java.util.Formatter
2838 // public static String format(Locale l, String format, Object ... args) {
2839 // return new Formatter(l).format(format, args).toString();
2843 * Returns the string representation of the <code>Object</code> argument.
2845 * @param obj an <code>Object</code>.
2846 * @return if the argument is <code>null</code>, then a string equal to
2847 * <code>"null"</code>; otherwise, the value of
2848 * <code>obj.toString()</code> is returned.
2849 * @see java.lang.Object#toString()
2851 public static String valueOf(Object obj) {
2852 return (obj == null) ? "null" : obj.toString();
2856 * Returns the string representation of the <code>char</code> array
2857 * argument. The contents of the character array are copied; subsequent
2858 * modification of the character array does not affect the newly
2861 * @param data a <code>char</code> array.
2862 * @return a newly allocated string representing the same sequence of
2863 * characters contained in the character array argument.
2865 public static String valueOf(char data[]) {
2866 return new String(data);
2870 * Returns the string representation of a specific subarray of the
2871 * <code>char</code> array argument.
2873 * The <code>offset</code> argument is the index of the first
2874 * character of the subarray. The <code>count</code> argument
2875 * specifies the length of the subarray. The contents of the subarray
2876 * are copied; subsequent modification of the character array does not
2877 * affect the newly created string.
2879 * @param data the character array.
2880 * @param offset the initial offset into the value of the
2881 * <code>String</code>.
2882 * @param count the length of the value of the <code>String</code>.
2883 * @return a string representing the sequence of characters contained
2884 * in the subarray of the character array argument.
2885 * @exception IndexOutOfBoundsException if <code>offset</code> is
2886 * negative, or <code>count</code> is negative, or
2887 * <code>offset+count</code> is larger than
2888 * <code>data.length</code>.
2890 public static String valueOf(char data[], int offset, int count) {
2891 return new String(data, offset, count);
2895 * Returns a String that represents the character sequence in the
2898 * @param data the character array.
2899 * @param offset initial offset of the subarray.
2900 * @param count length of the subarray.
2901 * @return a <code>String</code> that contains the characters of the
2902 * specified subarray of the character array.
2904 public static String copyValueOf(char data[], int offset, int count) {
2905 // All public String constructors now copy the data.
2906 return new String(data, offset, count);
2910 * Returns a String that represents the character sequence in the
2913 * @param data the character array.
2914 * @return a <code>String</code> that contains the characters of the
2917 public static String copyValueOf(char data[]) {
2918 return copyValueOf(data, 0, data.length);
2922 * Returns the string representation of the <code>boolean</code> argument.
2924 * @param b a <code>boolean</code>.
2925 * @return if the argument is <code>true</code>, a string equal to
2926 * <code>"true"</code> is returned; otherwise, a string equal to
2927 * <code>"false"</code> is returned.
2929 public static String valueOf(boolean b) {
2930 return b ? "true" : "false";
2934 * Returns the string representation of the <code>char</code>
2937 * @param c a <code>char</code>.
2938 * @return a string of length <code>1</code> containing
2939 * as its single character the argument <code>c</code>.
2941 public static String valueOf(char c) {
2943 return new String(data, 0, 1);
2947 * Returns the string representation of the <code>int</code> argument.
2949 * The representation is exactly the one returned by the
2950 * <code>Integer.toString</code> method of one argument.
2952 * @param i an <code>int</code>.
2953 * @return a string representation of the <code>int</code> argument.
2954 * @see java.lang.Integer#toString(int, int)
2956 public static String valueOf(int i) {
2957 return Integer.toString(i);
2961 * Returns the string representation of the <code>long</code> argument.
2963 * The representation is exactly the one returned by the
2964 * <code>Long.toString</code> method of one argument.
2966 * @param l a <code>long</code>.
2967 * @return a string representation of the <code>long</code> argument.
2968 * @see java.lang.Long#toString(long)
2970 public static String valueOf(long l) {
2971 return Long.toString(l);
2975 * Returns the string representation of the <code>float</code> argument.
2977 * The representation is exactly the one returned by the
2978 * <code>Float.toString</code> method of one argument.
2980 * @param f a <code>float</code>.
2981 * @return a string representation of the <code>float</code> argument.
2982 * @see java.lang.Float#toString(float)
2984 public static String valueOf(float f) {
2985 return Float.toString(f);
2989 * Returns the string representation of the <code>double</code> argument.
2991 * The representation is exactly the one returned by the
2992 * <code>Double.toString</code> method of one argument.
2994 * @param d a <code>double</code>.
2995 * @return a string representation of the <code>double</code> argument.
2996 * @see java.lang.Double#toString(double)
2998 public static String valueOf(double d) {
2999 return Double.toString(d);
3003 * Returns a canonical representation for the string object.
3005 * A pool of strings, initially empty, is maintained privately by the
3006 * class <code>String</code>.
3008 * When the intern method is invoked, if the pool already contains a
3009 * string equal to this <code>String</code> object as determined by
3010 * the {@link #equals(Object)} method, then the string from the pool is
3011 * returned. Otherwise, this <code>String</code> object is added to the
3012 * pool and a reference to this <code>String</code> object is returned.
3014 * It follows that for any two strings <code>s</code> and <code>t</code>,
3015 * <code>s.intern() == t.intern()</code> is <code>true</code>
3016 * if and only if <code>s.equals(t)</code> is <code>true</code>.
3018 * All literal strings and string-valued constant expressions are
3019 * interned. String literals are defined in section 3.10.5 of the
3020 * <cite>The Java™ Language Specification</cite>.
3022 * @return a string that has the same contents as this string, but is
3023 * guaranteed to be from a pool of unique strings.
3025 public native String intern();
3028 private static <T> T checkUTF8(T data, String charsetName)
3029 throws UnsupportedEncodingException {
3030 if (charsetName == null) {
3031 throw new NullPointerException("charsetName");
3033 if (!charsetName.equalsIgnoreCase("UTF-8")
3034 && !charsetName.equalsIgnoreCase("UTF8")) {
3035 throw new UnsupportedEncodingException(charsetName);
3040 private static int nextChar(byte[] arr, int[] index) throws IndexOutOfBoundsException {
3041 int c = arr[index[0]++] & 0xff;
3055 /* 110x xxxx 10xx xxxx*/
3056 int char2 = (int) arr[index[0]++];
3057 if ((char2 & 0xC0) != 0x80) {
3058 throw new IndexOutOfBoundsException("malformed input");
3060 return (((c & 0x1F) << 6) | (char2 & 0x3F));
3063 /* 1110 xxxx 10xx xxxx 10xx xxxx */
3064 int char2 = arr[index[0]++];
3065 int char3 = arr[index[0]++];
3066 if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80)) {
3067 throw new IndexOutOfBoundsException("malformed input");
3069 return (((c & 0x0F) << 12)
3070 | ((char2 & 0x3F) << 6)
3071 | ((char3 & 0x3F) << 0));
3074 /* 10xx xxxx, 1111 xxxx */
3075 throw new IndexOutOfBoundsException("malformed input");