Getting rid of the count, offset and value field in String. Replacing by delegation to real string r
2 * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
28 import java.util.Comparator;
29 import org.apidesign.bck2brwsr.core.ExtraJavaScript;
30 import org.apidesign.bck2brwsr.core.JavaScriptBody;
31 import org.apidesign.bck2brwsr.core.JavaScriptOnly;
32 import org.apidesign.bck2brwsr.core.JavaScriptPrototype;
35 * The <code>String</code> class represents character strings. All
36 * string literals in Java programs, such as <code>"abc"</code>, are
37 * implemented as instances of this class.
39 * Strings are constant; their values cannot be changed after they
40 * are created. String buffers support mutable strings.
41 * Because String objects are immutable they can be shared. For example:
42 * <p><blockquote><pre>
44 * </pre></blockquote><p>
46 * <p><blockquote><pre>
47 * char data[] = {'a', 'b', 'c'};
48 * String str = new String(data);
49 * </pre></blockquote><p>
50 * Here are some more examples of how strings can be used:
51 * <p><blockquote><pre>
52 * System.out.println("abc");
54 * System.out.println("abc" + cde);
55 * String c = "abc".substring(2,3);
56 * String d = cde.substring(1, 2);
59 * The class <code>String</code> includes methods for examining
60 * individual characters of the sequence, for comparing strings, for
61 * searching strings, for extracting substrings, and for creating a
62 * copy of a string with all characters translated to uppercase or to
63 * lowercase. Case mapping is based on the Unicode Standard version
64 * specified by the {@link java.lang.Character Character} class.
66 * The Java language provides special support for the string
67 * concatenation operator ( + ), and for conversion of
68 * other objects to strings. String concatenation is implemented
69 * through the <code>StringBuilder</code>(or <code>StringBuffer</code>)
70 * class and its <code>append</code> method.
71 * String conversions are implemented through the method
72 * <code>toString</code>, defined by <code>Object</code> and
73 * inherited by all classes in Java. For additional information on
74 * string concatenation and conversion, see Gosling, Joy, and Steele,
75 * <i>The Java Language Specification</i>.
77 * <p> Unless otherwise noted, passing a <tt>null</tt> argument to a constructor
78 * or method in this class will cause a {@link NullPointerException} to be
81 * <p>A <code>String</code> represents a string in the UTF-16 format
82 * in which <em>supplementary characters</em> are represented by <em>surrogate
83 * pairs</em> (see the section <a href="Character.html#unicode">Unicode
84 * Character Representations</a> in the <code>Character</code> class for
86 * Index values refer to <code>char</code> code units, so a supplementary
87 * character uses two positions in a <code>String</code>.
88 * <p>The <code>String</code> class provides methods for dealing with
89 * Unicode code points (i.e., characters), in addition to those for
90 * dealing with Unicode code units (i.e., <code>char</code> values).
93 * @author Arthur van Hoff
94 * @author Martin Buchholz
96 * @see java.lang.Object#toString()
97 * @see java.lang.StringBuffer
98 * @see java.lang.StringBuilder
99 * @see java.nio.charset.Charset
104 resource="/org/apidesign/vm4brwsr/emul/java_lang_String.js",
107 @JavaScriptPrototype(container = "String.prototype", prototype = "new String")
108 public final class String
109 implements java.io.Serializable, Comparable<String>, CharSequence
112 /** Cache the hash code for the string */
113 private int hash; // Default to 0
115 /** real string to delegate to */
118 /** use serialVersionUID from JDK 1.0.2 for interoperability */
119 private static final long serialVersionUID = -6849794470754667710L;
121 @JavaScriptOnly(name="toString", value="function() { return this.fld_r; }")
122 private static void jsToString() {
125 @JavaScriptOnly(name="valueOf", value="function() { return this.toString().valueOf(); }")
126 private static void jsValudOf() {
130 * Class String is special cased within the Serialization Stream Protocol.
132 * A String instance is written initially into an ObjectOutputStream in the
135 * <code>TC_STRING</code> (utf String)
137 * The String is written by method <code>DataOutput.writeUTF</code>.
138 * A new handle is generated to refer to all future references to the
139 * string instance within the stream.
141 // private static final ObjectStreamField[] serialPersistentFields =
142 // new ObjectStreamField[0];
145 * Initializes a newly created {@code String} object so that it represents
146 * an empty character sequence. Note that use of this constructor is
147 * unnecessary since Strings are immutable.
154 * Initializes a newly created {@code String} object so that it represents
155 * the same sequence of characters as the argument; in other words, the
156 * newly created string is a copy of the argument string. Unless an
157 * explicit copy of {@code original} is needed, use of this constructor is
158 * unnecessary since Strings are immutable.
163 public String(String original) {
164 this.r = original.toString();
168 * Allocates a new {@code String} so that it represents the sequence of
169 * characters currently contained in the character array argument. The
170 * contents of the character array are copied; subsequent modification of
171 * the character array does not affect the newly created string.
174 * The initial value of the string
176 @JavaScriptBody(args = { "self", "charArr" }, body=
177 "for (var i = 0; i < charArr.length; i++) {\n"
178 + " if (typeof charArr[i] === 'number') charArr[i] = String.fromCharCode(charArr[i]);\n"
180 + "self.fld_r = charArr.join('');\n"
182 public String(char value[]) {
186 * Allocates a new {@code String} that contains characters from a subarray
187 * of the character array argument. The {@code offset} argument is the
188 * index of the first character of the subarray and the {@code count}
189 * argument specifies the length of the subarray. The contents of the
190 * subarray are copied; subsequent modification of the character array does
191 * not affect the newly created string.
194 * Array that is the source of characters
202 * @throws IndexOutOfBoundsException
203 * If the {@code offset} and {@code count} arguments index
204 * characters outside the bounds of the {@code value} array
206 @JavaScriptBody(args = { "self", "charArr", "off", "cnt" }, body =
207 "var up = off + cnt;\n" +
208 "for (var i = off; i < up; i++) {\n" +
209 " if (typeof charArr[i] === 'number') charArr[i] = String.fromCharCode(charArr[i]);\n" +
211 "self.fld_r = charArr.slice(off, up).join(\"\");\n"
213 public String(char value[], int offset, int count) {
217 * Allocates a new {@code String} that contains characters from a subarray
218 * of the <a href="Character.html#unicode">Unicode code point</a> array
219 * argument. The {@code offset} argument is the index of the first code
220 * point of the subarray and the {@code count} argument specifies the
221 * length of the subarray. The contents of the subarray are converted to
222 * {@code char}s; subsequent modification of the {@code int} array does not
223 * affect the newly created string.
226 * Array that is the source of Unicode code points
234 * @throws IllegalArgumentException
235 * If any invalid Unicode code point is found in {@code
238 * @throws IndexOutOfBoundsException
239 * If the {@code offset} and {@code count} arguments index
240 * characters outside the bounds of the {@code codePoints} array
244 public String(int[] codePoints, int offset, int count) {
246 throw new StringIndexOutOfBoundsException(offset);
249 throw new StringIndexOutOfBoundsException(count);
251 // Note: offset or count might be near -1>>>1.
252 if (offset > codePoints.length - count) {
253 throw new StringIndexOutOfBoundsException(offset + count);
256 final int end = offset + count;
258 // Pass 1: Compute precise size of char[]
260 for (int i = offset; i < end; i++) {
261 int c = codePoints[i];
262 if (Character.isBmpCodePoint(c))
264 else if (Character.isValidCodePoint(c))
266 else throw new IllegalArgumentException(Integer.toString(c));
269 // Pass 2: Allocate and fill in char[]
270 final char[] v = new char[n];
272 for (int i = offset, j = 0; i < end; i++, j++) {
273 int c = codePoints[i];
274 if (Character.isBmpCodePoint(c))
277 Character.toSurrogates(c, v, j++);
280 this.r = new String(v, 0, n);
284 * Allocates a new {@code String} constructed from a subarray of an array
285 * of 8-bit integer values.
287 * <p> The {@code offset} argument is the index of the first byte of the
288 * subarray, and the {@code count} argument specifies the length of the
291 * <p> Each {@code byte} in the subarray is converted to a {@code char} as
292 * specified in the method above.
294 * @deprecated This method does not properly convert bytes into characters.
295 * As of JDK 1.1, the preferred way to do this is via the
296 * {@code String} constructors that take a {@link
297 * java.nio.charset.Charset}, charset name, or that use the platform's
301 * The bytes to be converted to characters
304 * The top 8 bits of each 16-bit Unicode code unit
311 * @throws IndexOutOfBoundsException
312 * If the {@code offset} or {@code count} argument is invalid
314 * @see #String(byte[], int)
315 * @see #String(byte[], int, int, java.lang.String)
316 * @see #String(byte[], int, int, java.nio.charset.Charset)
317 * @see #String(byte[], int, int)
318 * @see #String(byte[], java.lang.String)
319 * @see #String(byte[], java.nio.charset.Charset)
320 * @see #String(byte[])
323 public String(byte ascii[], int hibyte, int offset, int count) {
324 checkBounds(ascii, offset, count);
325 char value[] = new char[count];
328 for (int i = count ; i-- > 0 ;) {
329 value[i] = (char) (ascii[i + offset] & 0xff);
333 for (int i = count ; i-- > 0 ;) {
334 value[i] = (char) (hibyte | (ascii[i + offset] & 0xff));
337 this.r = new String(value, 0, count);
341 * Allocates a new {@code String} containing characters constructed from
342 * an array of 8-bit integer values. Each character <i>c</i>in the
343 * resulting string is constructed from the corresponding component
344 * <i>b</i> in the byte array such that:
347 * <b><i>c</i></b> == (char)(((hibyte & 0xff) << 8)
348 * | (<b><i>b</i></b> & 0xff))
349 * </pre></blockquote>
351 * @deprecated This method does not properly convert bytes into
352 * characters. As of JDK 1.1, the preferred way to do this is via the
353 * {@code String} constructors that take a {@link
354 * java.nio.charset.Charset}, charset name, or that use the platform's
358 * The bytes to be converted to characters
361 * The top 8 bits of each 16-bit Unicode code unit
363 * @see #String(byte[], int, int, java.lang.String)
364 * @see #String(byte[], int, int, java.nio.charset.Charset)
365 * @see #String(byte[], int, int)
366 * @see #String(byte[], java.lang.String)
367 * @see #String(byte[], java.nio.charset.Charset)
368 * @see #String(byte[])
371 public String(byte ascii[], int hibyte) {
372 this(ascii, hibyte, 0, ascii.length);
375 /* Common private utility method used to bounds check the byte array
376 * and requested offset & length values used by the String(byte[],..)
379 private static void checkBounds(byte[] bytes, int offset, int length) {
381 throw new StringIndexOutOfBoundsException(length);
383 throw new StringIndexOutOfBoundsException(offset);
384 if (offset > bytes.length - length)
385 throw new StringIndexOutOfBoundsException(offset + length);
389 * Constructs a new {@code String} by decoding the specified subarray of
390 * bytes using the specified charset. The length of the new {@code String}
391 * is a function of the charset, and hence may not be equal to the length
394 * <p> The behavior of this constructor when the given bytes are not valid
395 * in the given charset is unspecified. The {@link
396 * java.nio.charset.CharsetDecoder} class should be used when more control
397 * over the decoding process is required.
400 * The bytes to be decoded into characters
403 * The index of the first byte to decode
406 * The number of bytes to decode
409 * The name of a supported {@linkplain java.nio.charset.Charset
412 * @throws UnsupportedEncodingException
413 * If the named charset is not supported
415 * @throws IndexOutOfBoundsException
416 * If the {@code offset} and {@code length} arguments index
417 * characters outside the bounds of the {@code bytes} array
421 // public String(byte bytes[], int offset, int length, String charsetName)
422 // throws UnsupportedEncodingException
424 // if (charsetName == null)
425 // throw new NullPointerException("charsetName");
426 // checkBounds(bytes, offset, length);
427 // char[] v = StringCoding.decode(charsetName, bytes, offset, length);
429 // this.count = v.length;
434 * Constructs a new {@code String} by decoding the specified subarray of
435 * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
436 * The length of the new {@code String} is a function of the charset, and
437 * hence may not be equal to the length of the subarray.
439 * <p> This method always replaces malformed-input and unmappable-character
440 * sequences with this charset's default replacement string. The {@link
441 * java.nio.charset.CharsetDecoder} class should be used when more control
442 * over the decoding process is required.
445 * The bytes to be decoded into characters
448 * The index of the first byte to decode
451 * The number of bytes to decode
454 * The {@linkplain java.nio.charset.Charset charset} to be used to
455 * decode the {@code bytes}
457 * @throws IndexOutOfBoundsException
458 * If the {@code offset} and {@code length} arguments index
459 * characters outside the bounds of the {@code bytes} array
463 /* don't want dependnecy on Charset
464 public String(byte bytes[], int offset, int length, Charset charset) {
466 throw new NullPointerException("charset");
467 checkBounds(bytes, offset, length);
468 char[] v = StringCoding.decode(charset, bytes, offset, length);
470 this.count = v.length;
476 * Constructs a new {@code String} by decoding the specified array of bytes
477 * using the specified {@linkplain java.nio.charset.Charset charset}. The
478 * length of the new {@code String} is a function of the charset, and hence
479 * may not be equal to the length of the byte array.
481 * <p> The behavior of this constructor when the given bytes are not valid
482 * in the given charset is unspecified. The {@link
483 * java.nio.charset.CharsetDecoder} class should be used when more control
484 * over the decoding process is required.
487 * The bytes to be decoded into characters
490 * The name of a supported {@linkplain java.nio.charset.Charset
493 * @throws UnsupportedEncodingException
494 * If the named charset is not supported
498 // public String(byte bytes[], String charsetName)
499 // throws UnsupportedEncodingException
501 // this(bytes, 0, bytes.length, charsetName);
505 * Constructs a new {@code String} by decoding the specified array of
506 * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
507 * The length of the new {@code String} is a function of the charset, and
508 * hence may not be equal to the length of the byte array.
510 * <p> This method always replaces malformed-input and unmappable-character
511 * sequences with this charset's default replacement string. The {@link
512 * java.nio.charset.CharsetDecoder} class should be used when more control
513 * over the decoding process is required.
516 * The bytes to be decoded into characters
519 * The {@linkplain java.nio.charset.Charset charset} to be used to
520 * decode the {@code bytes}
524 /* don't want dep on Charset
525 public String(byte bytes[], Charset charset) {
526 this(bytes, 0, bytes.length, charset);
531 * Constructs a new {@code String} by decoding the specified subarray of
532 * bytes using the platform's default charset. The length of the new
533 * {@code String} is a function of the charset, and hence may not be equal
534 * to the length of the subarray.
536 * <p> The behavior of this constructor when the given bytes are not valid
537 * in the default charset is unspecified. The {@link
538 * java.nio.charset.CharsetDecoder} class should be used when more control
539 * over the decoding process is required.
542 * The bytes to be decoded into characters
545 * The index of the first byte to decode
548 * The number of bytes to decode
550 * @throws IndexOutOfBoundsException
551 * If the {@code offset} and the {@code length} arguments index
552 * characters outside the bounds of the {@code bytes} array
556 public String(byte bytes[], int offset, int length) {
557 checkBounds(bytes, offset, length);
558 char[] v = new char[length];
559 for (int i = 0; i < length; i++) {
560 v[i] = (char)bytes[offset++];
562 this.r = new String(v, 0, v.length);
566 * Constructs a new {@code String} by decoding the specified array of bytes
567 * using the platform's default charset. The length of the new {@code
568 * String} is a function of the charset, and hence may not be equal to the
569 * length of the byte array.
571 * <p> The behavior of this constructor when the given bytes are not valid
572 * in the default charset is unspecified. The {@link
573 * java.nio.charset.CharsetDecoder} class should be used when more control
574 * over the decoding process is required.
577 * The bytes to be decoded into characters
581 public String(byte bytes[]) {
582 this(bytes, 0, bytes.length);
586 * Allocates a new string that contains the sequence of characters
587 * currently contained in the string buffer argument. The contents of the
588 * string buffer are copied; subsequent modification of the string buffer
589 * does not affect the newly created string.
592 * A {@code StringBuffer}
594 public String(StringBuffer buffer) {
595 this.r = buffer.toString();
599 * Allocates a new string that contains the sequence of characters
600 * currently contained in the string builder argument. The contents of the
601 * string builder are copied; subsequent modification of the string builder
602 * does not affect the newly created string.
604 * <p> This constructor is provided to ease migration to {@code
605 * StringBuilder}. Obtaining a string from a string builder via the {@code
606 * toString} method is likely to run faster and is generally preferred.
609 * A {@code StringBuilder}
613 public String(StringBuilder builder) {
614 this.r = builder.toString();
618 * Returns the length of this string.
619 * The length is equal to the number of <a href="Character.html#unicode">Unicode
620 * code units</a> in the string.
622 * @return the length of the sequence of characters represented by this
625 @JavaScriptBody(args = "self", body = "return self.toString().length;")
626 public int length() {
627 throw new UnsupportedOperationException();
631 * Returns <tt>true</tt> if, and only if, {@link #length()} is <tt>0</tt>.
633 * @return <tt>true</tt> if {@link #length()} is <tt>0</tt>, otherwise
638 @JavaScriptBody(args = "self", body="return self.toString().length === 0;")
639 public boolean isEmpty() {
640 return length() == 0;
644 * Returns the <code>char</code> value at the
645 * specified index. An index ranges from <code>0</code> to
646 * <code>length() - 1</code>. The first <code>char</code> value of the sequence
647 * is at index <code>0</code>, the next at index <code>1</code>,
648 * and so on, as for array indexing.
650 * <p>If the <code>char</code> value specified by the index is a
651 * <a href="Character.html#unicode">surrogate</a>, the surrogate
654 * @param index the index of the <code>char</code> value.
655 * @return the <code>char</code> value at the specified index of this string.
656 * The first <code>char</code> value is at index <code>0</code>.
657 * @exception IndexOutOfBoundsException if the <code>index</code>
658 * argument is negative or not less than the length of this
661 @JavaScriptBody(args = { "self", "index" },
662 body = "return self.toString().charCodeAt(index);"
664 public char charAt(int index) {
665 throw new UnsupportedOperationException();
669 * Returns the character (Unicode code point) at the specified
670 * index. The index refers to <code>char</code> values
671 * (Unicode code units) and ranges from <code>0</code> to
672 * {@link #length()}<code> - 1</code>.
674 * <p> If the <code>char</code> value specified at the given index
675 * is in the high-surrogate range, the following index is less
676 * than the length of this <code>String</code>, and the
677 * <code>char</code> value at the following index is in the
678 * low-surrogate range, then the supplementary code point
679 * corresponding to this surrogate pair is returned. Otherwise,
680 * the <code>char</code> value at the given index is returned.
682 * @param index the index to the <code>char</code> values
683 * @return the code point value of the character at the
685 * @exception IndexOutOfBoundsException if the <code>index</code>
686 * argument is negative or not less than the length of this
690 public int codePointAt(int index) {
691 if ((index < 0) || (index >= length())) {
692 throw new StringIndexOutOfBoundsException(index);
694 return Character.codePointAtImpl(toCharArray(), offset() + index, offset() + length());
698 * Returns the character (Unicode code point) before the specified
699 * index. The index refers to <code>char</code> values
700 * (Unicode code units) and ranges from <code>1</code> to {@link
701 * CharSequence#length() length}.
703 * <p> If the <code>char</code> value at <code>(index - 1)</code>
704 * is in the low-surrogate range, <code>(index - 2)</code> is not
705 * negative, and the <code>char</code> value at <code>(index -
706 * 2)</code> is in the high-surrogate range, then the
707 * supplementary code point value of the surrogate pair is
708 * returned. If the <code>char</code> value at <code>index -
709 * 1</code> is an unpaired low-surrogate or a high-surrogate, the
710 * surrogate value is returned.
712 * @param index the index following the code point that should be returned
713 * @return the Unicode code point value before the given index.
714 * @exception IndexOutOfBoundsException if the <code>index</code>
715 * argument is less than 1 or greater than the length
719 public int codePointBefore(int index) {
721 if ((i < 0) || (i >= length())) {
722 throw new StringIndexOutOfBoundsException(index);
724 return Character.codePointBeforeImpl(toCharArray(), offset() + index, offset());
728 * Returns the number of Unicode code points in the specified text
729 * range of this <code>String</code>. The text range begins at the
730 * specified <code>beginIndex</code> and extends to the
731 * <code>char</code> at index <code>endIndex - 1</code>. Thus the
732 * length (in <code>char</code>s) of the text range is
733 * <code>endIndex-beginIndex</code>. Unpaired surrogates within
734 * the text range count as one code point each.
736 * @param beginIndex the index to the first <code>char</code> of
738 * @param endIndex the index after the last <code>char</code> of
740 * @return the number of Unicode code points in the specified text
742 * @exception IndexOutOfBoundsException if the
743 * <code>beginIndex</code> is negative, or <code>endIndex</code>
744 * is larger than the length of this <code>String</code>, or
745 * <code>beginIndex</code> is larger than <code>endIndex</code>.
748 public int codePointCount(int beginIndex, int endIndex) {
749 if (beginIndex < 0 || endIndex > length() || beginIndex > endIndex) {
750 throw new IndexOutOfBoundsException();
752 return Character.codePointCountImpl(toCharArray(), offset()+beginIndex, endIndex-beginIndex);
756 * Returns the index within this <code>String</code> that is
757 * offset from the given <code>index</code> by
758 * <code>codePointOffset</code> code points. Unpaired surrogates
759 * within the text range given by <code>index</code> and
760 * <code>codePointOffset</code> count as one code point each.
762 * @param index the index to be offset
763 * @param codePointOffset the offset in code points
764 * @return the index within this <code>String</code>
765 * @exception IndexOutOfBoundsException if <code>index</code>
766 * is negative or larger then the length of this
767 * <code>String</code>, or if <code>codePointOffset</code> is positive
768 * and the substring starting with <code>index</code> has fewer
769 * than <code>codePointOffset</code> code points,
770 * or if <code>codePointOffset</code> is negative and the substring
771 * before <code>index</code> has fewer than the absolute value
772 * of <code>codePointOffset</code> code points.
775 public int offsetByCodePoints(int index, int codePointOffset) {
776 if (index < 0 || index > length()) {
777 throw new IndexOutOfBoundsException();
779 return Character.offsetByCodePointsImpl(toCharArray(), offset(), length(),
780 offset()+index, codePointOffset) - offset();
784 * Copy characters from this string into dst starting at dstBegin.
785 * This method doesn't perform any range checking.
787 @JavaScriptBody(args = { "self", "arr", "to" }, body =
788 "var s = self.toString();\n" +
789 "for (var i = 0; i < s.length; i++) {\n" +
790 " arr[to++] = s[i];\n" +
793 void getChars(char dst[], int dstBegin) {
794 AbstractStringBuilder.arraycopy(toCharArray(), offset(), dst, dstBegin, length());
798 * Copies characters from this string into the destination character
801 * The first character to be copied is at index <code>srcBegin</code>;
802 * the last character to be copied is at index <code>srcEnd-1</code>
803 * (thus the total number of characters to be copied is
804 * <code>srcEnd-srcBegin</code>). The characters are copied into the
805 * subarray of <code>dst</code> starting at index <code>dstBegin</code>
806 * and ending at index:
807 * <p><blockquote><pre>
808 * dstbegin + (srcEnd-srcBegin) - 1
809 * </pre></blockquote>
811 * @param srcBegin index of the first character in the string
813 * @param srcEnd index after the last character in the string
815 * @param dst the destination array.
816 * @param dstBegin the start offset in the destination array.
817 * @exception IndexOutOfBoundsException If any of the following
819 * <ul><li><code>srcBegin</code> is negative.
820 * <li><code>srcBegin</code> is greater than <code>srcEnd</code>
821 * <li><code>srcEnd</code> is greater than the length of this
823 * <li><code>dstBegin</code> is negative
824 * <li><code>dstBegin+(srcEnd-srcBegin)</code> is larger than
825 * <code>dst.length</code></ul>
827 @JavaScriptBody(args = { "self", "beg", "end", "arr", "dst" }, body=
828 "var s = self.toString();\n" +
829 "while (beg < end) {\n" +
830 " arr[dst++] = s[beg++];\n" +
833 public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
835 throw new StringIndexOutOfBoundsException(srcBegin);
837 if (srcEnd > length()) {
838 throw new StringIndexOutOfBoundsException(srcEnd);
840 if (srcBegin > srcEnd) {
841 throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
843 AbstractStringBuilder.arraycopy(toCharArray(), offset() + srcBegin, dst, dstBegin,
848 * Copies characters from this string into the destination byte array. Each
849 * byte receives the 8 low-order bits of the corresponding character. The
850 * eight high-order bits of each character are not copied and do not
851 * participate in the transfer in any way.
853 * <p> The first character to be copied is at index {@code srcBegin}; the
854 * last character to be copied is at index {@code srcEnd-1}. The total
855 * number of characters to be copied is {@code srcEnd-srcBegin}. The
856 * characters, converted to bytes, are copied into the subarray of {@code
857 * dst} starting at index {@code dstBegin} and ending at index:
860 * dstbegin + (srcEnd-srcBegin) - 1
861 * </pre></blockquote>
863 * @deprecated This method does not properly convert characters into
864 * bytes. As of JDK 1.1, the preferred way to do this is via the
865 * {@link #getBytes()} method, which uses the platform's default charset.
868 * Index of the first character in the string to copy
871 * Index after the last character in the string to copy
874 * The destination array
877 * The start offset in the destination array
879 * @throws IndexOutOfBoundsException
880 * If any of the following is true:
882 * <li> {@code srcBegin} is negative
883 * <li> {@code srcBegin} is greater than {@code srcEnd}
884 * <li> {@code srcEnd} is greater than the length of this String
885 * <li> {@code dstBegin} is negative
886 * <li> {@code dstBegin+(srcEnd-srcBegin)} is larger than {@code
891 public void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin) {
893 throw new StringIndexOutOfBoundsException(srcBegin);
895 if (srcEnd > length()) {
896 throw new StringIndexOutOfBoundsException(srcEnd);
898 if (srcBegin > srcEnd) {
899 throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
902 int n = offset() + srcEnd;
903 int i = offset() + srcBegin;
904 char[] val = toCharArray(); /* avoid getfield opcode */
907 dst[j++] = (byte)val[i++];
912 * Encodes this {@code String} into a sequence of bytes using the named
913 * charset, storing the result into a new byte array.
915 * <p> The behavior of this method when this string cannot be encoded in
916 * the given charset is unspecified. The {@link
917 * java.nio.charset.CharsetEncoder} class should be used when more control
918 * over the encoding process is required.
921 * The name of a supported {@linkplain java.nio.charset.Charset
924 * @return The resultant byte array
926 * @throws UnsupportedEncodingException
927 * If the named charset is not supported
931 // public byte[] getBytes(String charsetName)
932 // throws UnsupportedEncodingException
934 // if (charsetName == null) throw new NullPointerException();
935 // return StringCoding.encode(charsetName, value, offset, count);
939 * Encodes this {@code String} into a sequence of bytes using the given
940 * {@linkplain java.nio.charset.Charset charset}, storing the result into a
943 * <p> This method always replaces malformed-input and unmappable-character
944 * sequences with this charset's default replacement byte array. The
945 * {@link java.nio.charset.CharsetEncoder} class should be used when more
946 * control over the encoding process is required.
949 * The {@linkplain java.nio.charset.Charset} to be used to encode
952 * @return The resultant byte array
956 /* don't want dep on Charset
957 public byte[] getBytes(Charset charset) {
958 if (charset == null) throw new NullPointerException();
959 return StringCoding.encode(charset, value, offset, count);
964 * Encodes this {@code String} into a sequence of bytes using the
965 * platform's default charset, storing the result into a new byte array.
967 * <p> The behavior of this method when this string cannot be encoded in
968 * the default charset is unspecified. The {@link
969 * java.nio.charset.CharsetEncoder} class should be used when more control
970 * over the encoding process is required.
972 * @return The resultant byte array
976 public byte[] getBytes() {
977 byte[] arr = new byte[length()];
978 for (int i = 0; i < arr.length; i++) {
979 final char v = charAt(i);
986 * Compares this string to the specified object. The result is {@code
987 * true} if and only if the argument is not {@code null} and is a {@code
988 * String} object that represents the same sequence of characters as this
992 * The object to compare this {@code String} against
994 * @return {@code true} if the given object represents a {@code String}
995 * equivalent to this string, {@code false} otherwise
997 * @see #compareTo(String)
998 * @see #equalsIgnoreCase(String)
1000 @JavaScriptBody(args = { "self", "obj" }, body =
1001 "return obj.$instOf_java_lang_String && "
1002 + "self.toString() === obj.toString();"
1004 public boolean equals(Object anObject) {
1005 if (this == anObject) {
1008 if (anObject instanceof String) {
1009 String anotherString = (String)anObject;
1011 if (n == anotherString.length()) {
1012 char v1[] = toCharArray();
1013 char v2[] = anotherString.toCharArray();
1015 int j = anotherString.offset();
1017 if (v1[i++] != v2[j++])
1027 * Compares this string to the specified {@code StringBuffer}. The result
1028 * is {@code true} if and only if this {@code String} represents the same
1029 * sequence of characters as the specified {@code StringBuffer}.
1032 * The {@code StringBuffer} to compare this {@code String} against
1034 * @return {@code true} if this {@code String} represents the same
1035 * sequence of characters as the specified {@code StringBuffer},
1036 * {@code false} otherwise
1040 public boolean contentEquals(StringBuffer sb) {
1042 return contentEquals((CharSequence)sb);
1047 * Compares this string to the specified {@code CharSequence}. The result
1048 * is {@code true} if and only if this {@code String} represents the same
1049 * sequence of char values as the specified sequence.
1052 * The sequence to compare this {@code String} against
1054 * @return {@code true} if this {@code String} represents the same
1055 * sequence of char values as the specified sequence, {@code
1060 public boolean contentEquals(CharSequence cs) {
1061 if (length() != cs.length())
1063 // Argument is a StringBuffer, StringBuilder
1064 if (cs instanceof AbstractStringBuilder) {
1065 char v1[] = toCharArray();
1066 char v2[] = ((AbstractStringBuilder)cs).getValue();
1071 if (v1[i++] != v2[j++])
1076 // Argument is a String
1077 if (cs.equals(this))
1079 // Argument is a generic CharSequence
1080 char v1[] = toCharArray();
1085 if (v1[i++] != cs.charAt(j++))
1092 * Compares this {@code String} to another {@code String}, ignoring case
1093 * considerations. Two strings are considered equal ignoring case if they
1094 * are of the same length and corresponding characters in the two strings
1095 * are equal ignoring case.
1097 * <p> Two characters {@code c1} and {@code c2} are considered the same
1098 * ignoring case if at least one of the following is true:
1100 * <li> The two characters are the same (as compared by the
1101 * {@code ==} operator)
1102 * <li> Applying the method {@link
1103 * java.lang.Character#toUpperCase(char)} to each character
1104 * produces the same result
1105 * <li> Applying the method {@link
1106 * java.lang.Character#toLowerCase(char)} to each character
1107 * produces the same result
1110 * @param anotherString
1111 * The {@code String} to compare this {@code String} against
1113 * @return {@code true} if the argument is not {@code null} and it
1114 * represents an equivalent {@code String} ignoring case; {@code
1117 * @see #equals(Object)
1119 public boolean equalsIgnoreCase(String anotherString) {
1120 return (this == anotherString) ? true :
1121 (anotherString != null) && (anotherString.length() == length()) &&
1122 regionMatches(true, 0, anotherString, 0, length());
1126 * Compares two strings lexicographically.
1127 * The comparison is based on the Unicode value of each character in
1128 * the strings. The character sequence represented by this
1129 * <code>String</code> object is compared lexicographically to the
1130 * character sequence represented by the argument string. The result is
1131 * a negative integer if this <code>String</code> object
1132 * lexicographically precedes the argument string. The result is a
1133 * positive integer if this <code>String</code> object lexicographically
1134 * follows the argument string. The result is zero if the strings
1135 * are equal; <code>compareTo</code> returns <code>0</code> exactly when
1136 * the {@link #equals(Object)} method would return <code>true</code>.
1138 * This is the definition of lexicographic ordering. If two strings are
1139 * different, then either they have different characters at some index
1140 * that is a valid index for both strings, or their lengths are different,
1141 * or both. If they have different characters at one or more index
1142 * positions, let <i>k</i> be the smallest such index; then the string
1143 * whose character at position <i>k</i> has the smaller value, as
1144 * determined by using the < operator, lexicographically precedes the
1145 * other string. In this case, <code>compareTo</code> returns the
1146 * difference of the two character values at position <code>k</code> in
1147 * the two string -- that is, the value:
1149 * this.charAt(k)-anotherString.charAt(k)
1150 * </pre></blockquote>
1151 * If there is no index position at which they differ, then the shorter
1152 * string lexicographically precedes the longer string. In this case,
1153 * <code>compareTo</code> returns the difference of the lengths of the
1154 * strings -- that is, the value:
1156 * this.length()-anotherString.length()
1157 * </pre></blockquote>
1159 * @param anotherString the <code>String</code> to be compared.
1160 * @return the value <code>0</code> if the argument string is equal to
1161 * this string; a value less than <code>0</code> if this string
1162 * is lexicographically less than the string argument; and a
1163 * value greater than <code>0</code> if this string is
1164 * lexicographically greater than the string argument.
1166 public int compareTo(String anotherString) {
1167 int len1 = length();
1168 int len2 = anotherString.length();
1169 int n = Math.min(len1, len2);
1170 char v1[] = toCharArray();
1171 char v2[] = anotherString.toCharArray();
1173 int j = anotherString.offset();
1199 * A Comparator that orders <code>String</code> objects as by
1200 * <code>compareToIgnoreCase</code>. This comparator is serializable.
1202 * Note that this Comparator does <em>not</em> take locale into account,
1203 * and will result in an unsatisfactory ordering for certain locales.
1204 * The java.text package provides <em>Collators</em> to allow
1205 * locale-sensitive ordering.
1207 * @see java.text.Collator#compare(String, String)
1210 public static final Comparator<String> CASE_INSENSITIVE_ORDER
1211 = new CaseInsensitiveComparator();
1213 private static int offset() {
1217 private static class CaseInsensitiveComparator
1218 implements Comparator<String>, java.io.Serializable {
1219 // use serialVersionUID from JDK 1.2.2 for interoperability
1220 private static final long serialVersionUID = 8575799808933029326L;
1222 public int compare(String s1, String s2) {
1223 int n1 = s1.length();
1224 int n2 = s2.length();
1225 int min = Math.min(n1, n2);
1226 for (int i = 0; i < min; i++) {
1227 char c1 = s1.charAt(i);
1228 char c2 = s2.charAt(i);
1230 c1 = Character.toUpperCase(c1);
1231 c2 = Character.toUpperCase(c2);
1233 c1 = Character.toLowerCase(c1);
1234 c2 = Character.toLowerCase(c2);
1236 // No overflow because of numeric promotion
1247 * Compares two strings lexicographically, ignoring case
1248 * differences. This method returns an integer whose sign is that of
1249 * calling <code>compareTo</code> with normalized versions of the strings
1250 * where case differences have been eliminated by calling
1251 * <code>Character.toLowerCase(Character.toUpperCase(character))</code> on
1254 * Note that this method does <em>not</em> take locale into account,
1255 * and will result in an unsatisfactory ordering for certain locales.
1256 * The java.text package provides <em>collators</em> to allow
1257 * locale-sensitive ordering.
1259 * @param str the <code>String</code> to be compared.
1260 * @return a negative integer, zero, or a positive integer as the
1261 * specified String is greater than, equal to, or less
1262 * than this String, ignoring case considerations.
1263 * @see java.text.Collator#compare(String, String)
1266 public int compareToIgnoreCase(String str) {
1267 return CASE_INSENSITIVE_ORDER.compare(this, str);
1271 * Tests if two string regions are equal.
1273 * A substring of this <tt>String</tt> object is compared to a substring
1274 * of the argument other. The result is true if these substrings
1275 * represent identical character sequences. The substring of this
1276 * <tt>String</tt> object to be compared begins at index <tt>toffset</tt>
1277 * and has length <tt>len</tt>. The substring of other to be compared
1278 * begins at index <tt>ooffset</tt> and has length <tt>len</tt>. The
1279 * result is <tt>false</tt> if and only if at least one of the following
1281 * <ul><li><tt>toffset</tt> is negative.
1282 * <li><tt>ooffset</tt> is negative.
1283 * <li><tt>toffset+len</tt> is greater than the length of this
1284 * <tt>String</tt> object.
1285 * <li><tt>ooffset+len</tt> is greater than the length of the other
1287 * <li>There is some nonnegative integer <i>k</i> less than <tt>len</tt>
1289 * <tt>this.charAt(toffset+<i>k</i>) != other.charAt(ooffset+<i>k</i>)</tt>
1292 * @param toffset the starting offset of the subregion in this string.
1293 * @param other the string argument.
1294 * @param ooffset the starting offset of the subregion in the string
1296 * @param len the number of characters to compare.
1297 * @return <code>true</code> if the specified subregion of this string
1298 * exactly matches the specified subregion of the string argument;
1299 * <code>false</code> otherwise.
1301 public boolean regionMatches(int toffset, String other, int ooffset,
1303 char ta[] = toCharArray();
1304 int to = offset() + toffset;
1305 char pa[] = other.toCharArray();
1306 int po = other.offset() + ooffset;
1307 // Note: toffset, ooffset, or len might be near -1>>>1.
1308 if ((ooffset < 0) || (toffset < 0) || (toffset > (long)length() - len)
1309 || (ooffset > (long)other.length() - len)) {
1313 if (ta[to++] != pa[po++]) {
1321 * Tests if two string regions are equal.
1323 * A substring of this <tt>String</tt> object is compared to a substring
1324 * of the argument <tt>other</tt>. The result is <tt>true</tt> if these
1325 * substrings represent character sequences that are the same, ignoring
1326 * case if and only if <tt>ignoreCase</tt> is true. The substring of
1327 * this <tt>String</tt> object to be compared begins at index
1328 * <tt>toffset</tt> and has length <tt>len</tt>. The substring of
1329 * <tt>other</tt> to be compared begins at index <tt>ooffset</tt> and
1330 * has length <tt>len</tt>. The result is <tt>false</tt> if and only if
1331 * at least one of the following is true:
1332 * <ul><li><tt>toffset</tt> is negative.
1333 * <li><tt>ooffset</tt> is negative.
1334 * <li><tt>toffset+len</tt> is greater than the length of this
1335 * <tt>String</tt> object.
1336 * <li><tt>ooffset+len</tt> is greater than the length of the other
1338 * <li><tt>ignoreCase</tt> is <tt>false</tt> and there is some nonnegative
1339 * integer <i>k</i> less than <tt>len</tt> such that:
1341 * this.charAt(toffset+k) != other.charAt(ooffset+k)
1342 * </pre></blockquote>
1343 * <li><tt>ignoreCase</tt> is <tt>true</tt> and there is some nonnegative
1344 * integer <i>k</i> less than <tt>len</tt> such that:
1346 * Character.toLowerCase(this.charAt(toffset+k)) !=
1347 Character.toLowerCase(other.charAt(ooffset+k))
1348 * </pre></blockquote>
1351 * Character.toUpperCase(this.charAt(toffset+k)) !=
1352 * Character.toUpperCase(other.charAt(ooffset+k))
1353 * </pre></blockquote>
1356 * @param ignoreCase if <code>true</code>, ignore case when comparing
1358 * @param toffset the starting offset of the subregion in this
1360 * @param other the string argument.
1361 * @param ooffset the starting offset of the subregion in the string
1363 * @param len the number of characters to compare.
1364 * @return <code>true</code> if the specified subregion of this string
1365 * matches the specified subregion of the string argument;
1366 * <code>false</code> otherwise. Whether the matching is exact
1367 * or case insensitive depends on the <code>ignoreCase</code>
1370 public boolean regionMatches(boolean ignoreCase, int toffset,
1371 String other, int ooffset, int len) {
1372 char ta[] = toCharArray();
1373 int to = offset() + toffset;
1374 char pa[] = other.toCharArray();
1375 int po = other.offset() + ooffset;
1376 // Note: toffset, ooffset, or len might be near -1>>>1.
1377 if ((ooffset < 0) || (toffset < 0) || (toffset > (long)length() - len) ||
1378 (ooffset > (long)other.length() - len)) {
1388 // If characters don't match but case may be ignored,
1389 // try converting both characters to uppercase.
1390 // If the results match, then the comparison scan should
1392 char u1 = Character.toUpperCase(c1);
1393 char u2 = Character.toUpperCase(c2);
1397 // Unfortunately, conversion to uppercase does not work properly
1398 // for the Georgian alphabet, which has strange rules about case
1399 // conversion. So we need to make one last check before
1401 if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) {
1411 * Tests if the substring of this string beginning at the
1412 * specified index starts with the specified prefix.
1414 * @param prefix the prefix.
1415 * @param toffset where to begin looking in this string.
1416 * @return <code>true</code> if the character sequence represented by the
1417 * argument is a prefix of the substring of this object starting
1418 * at index <code>toffset</code>; <code>false</code> otherwise.
1419 * The result is <code>false</code> if <code>toffset</code> is
1420 * negative or greater than the length of this
1421 * <code>String</code> object; otherwise the result is the same
1422 * as the result of the expression
1424 * this.substring(toffset).startsWith(prefix)
1427 @JavaScriptBody(args = { "self", "find", "from" }, body=
1428 "find = find.toString();\n" +
1429 "return self.toString().substring(from, find.length) === find;\n"
1431 public boolean startsWith(String prefix, int toffset) {
1432 char ta[] = toCharArray();
1433 int to = offset() + toffset;
1434 char pa[] = prefix.toCharArray();
1435 int po = prefix.offset();
1436 int pc = prefix.length();
1437 // Note: toffset might be near -1>>>1.
1438 if ((toffset < 0) || (toffset > length() - pc)) {
1442 if (ta[to++] != pa[po++]) {
1450 * Tests if this string starts with the specified prefix.
1452 * @param prefix the prefix.
1453 * @return <code>true</code> if the character sequence represented by the
1454 * argument is a prefix of the character sequence represented by
1455 * this string; <code>false</code> otherwise.
1456 * Note also that <code>true</code> will be returned if the
1457 * argument is an empty string or is equal to this
1458 * <code>String</code> object as determined by the
1459 * {@link #equals(Object)} method.
1462 public boolean startsWith(String prefix) {
1463 return startsWith(prefix, 0);
1467 * Tests if this string ends with the specified suffix.
1469 * @param suffix the suffix.
1470 * @return <code>true</code> if the character sequence represented by the
1471 * argument is a suffix of the character sequence represented by
1472 * this object; <code>false</code> otherwise. Note that the
1473 * result will be <code>true</code> if the argument is the
1474 * empty string or is equal to this <code>String</code> object
1475 * as determined by the {@link #equals(Object)} method.
1477 public boolean endsWith(String suffix) {
1478 return startsWith(suffix, length() - suffix.length());
1482 * Returns a hash code for this string. The hash code for a
1483 * <code>String</code> object is computed as
1485 * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
1486 * </pre></blockquote>
1487 * using <code>int</code> arithmetic, where <code>s[i]</code> is the
1488 * <i>i</i>th character of the string, <code>n</code> is the length of
1489 * the string, and <code>^</code> indicates exponentiation.
1490 * (The hash value of the empty string is zero.)
1492 * @return a hash code value for this object.
1494 @JavaScriptBody(args = "self", body =
1496 "var s = self.toString();\n" +
1497 "for (var i = 0; i < s.length; i++) {\n" +
1498 " var high = (h >> 16) & 0xffff, low = h & 0xffff;\n" +
1499 " h = (((((31 * high) & 0xffff) << 16) >>> 0) + (31 * low) + s.charCodeAt(i)) & 0xffffffff;\n" +
1503 public int hashCode() {
1505 if (h == 0 && length() > 0) {
1507 char val[] = toCharArray();
1510 for (int i = 0; i < len; i++) {
1511 h = 31*h + val[off++];
1519 * Returns the index within this string of the first occurrence of
1520 * the specified character. If a character with value
1521 * <code>ch</code> occurs in the character sequence represented by
1522 * this <code>String</code> object, then the index (in Unicode
1523 * code units) of the first such occurrence is returned. For
1524 * values of <code>ch</code> in the range from 0 to 0xFFFF
1525 * (inclusive), this is the smallest value <i>k</i> such that:
1527 * this.charAt(<i>k</i>) == ch
1528 * </pre></blockquote>
1529 * is true. For other values of <code>ch</code>, it is the
1530 * smallest value <i>k</i> such that:
1532 * this.codePointAt(<i>k</i>) == ch
1533 * </pre></blockquote>
1534 * is true. In either case, if no such character occurs in this
1535 * string, then <code>-1</code> is returned.
1537 * @param ch a character (Unicode code point).
1538 * @return the index of the first occurrence of the character in the
1539 * character sequence represented by this object, or
1540 * <code>-1</code> if the character does not occur.
1542 public int indexOf(int ch) {
1543 return indexOf(ch, 0);
1547 * Returns the index within this string of the first occurrence of the
1548 * specified character, starting the search at the specified index.
1550 * If a character with value <code>ch</code> occurs in the
1551 * character sequence represented by this <code>String</code>
1552 * object at an index no smaller than <code>fromIndex</code>, then
1553 * the index of the first such occurrence is returned. For values
1554 * of <code>ch</code> in the range from 0 to 0xFFFF (inclusive),
1555 * this is the smallest value <i>k</i> such that:
1557 * (this.charAt(<i>k</i>) == ch) && (<i>k</i> >= fromIndex)
1558 * </pre></blockquote>
1559 * is true. For other values of <code>ch</code>, it is the
1560 * smallest value <i>k</i> such that:
1562 * (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> >= fromIndex)
1563 * </pre></blockquote>
1564 * is true. In either case, if no such character occurs in this
1565 * string at or after position <code>fromIndex</code>, then
1566 * <code>-1</code> is returned.
1569 * There is no restriction on the value of <code>fromIndex</code>. If it
1570 * is negative, it has the same effect as if it were zero: this entire
1571 * string may be searched. If it is greater than the length of this
1572 * string, it has the same effect as if it were equal to the length of
1573 * this string: <code>-1</code> is returned.
1575 * <p>All indices are specified in <code>char</code> values
1576 * (Unicode code units).
1578 * @param ch a character (Unicode code point).
1579 * @param fromIndex the index to start the search from.
1580 * @return the index of the first occurrence of the character in the
1581 * character sequence represented by this object that is greater
1582 * than or equal to <code>fromIndex</code>, or <code>-1</code>
1583 * if the character does not occur.
1585 @JavaScriptBody(args = { "self", "ch", "from" }, body =
1586 "if (typeof ch === 'number') ch = String.fromCharCode(ch);\n" +
1587 "return self.toString().indexOf(ch, from);\n"
1589 public int indexOf(int ch, int fromIndex) {
1590 if (fromIndex < 0) {
1592 } else if (fromIndex >= length()) {
1593 // Note: fromIndex might be near -1>>>1.
1597 if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
1598 // handle most cases here (ch is a BMP code point or a
1599 // negative value (invalid code point))
1600 final char[] value = this.toCharArray();
1601 final int offset = this.offset();
1602 final int max = offset + length();
1603 for (int i = offset + fromIndex; i < max ; i++) {
1604 if (value[i] == ch) {
1610 return indexOfSupplementary(ch, fromIndex);
1615 * Handles (rare) calls of indexOf with a supplementary character.
1617 private int indexOfSupplementary(int ch, int fromIndex) {
1618 if (Character.isValidCodePoint(ch)) {
1619 final char[] value = this.toCharArray();
1620 final int offset = this.offset();
1621 final char hi = Character.highSurrogate(ch);
1622 final char lo = Character.lowSurrogate(ch);
1623 final int max = offset + length() - 1;
1624 for (int i = offset + fromIndex; i < max; i++) {
1625 if (value[i] == hi && value[i+1] == lo) {
1634 * Returns the index within this string of the last occurrence of
1635 * the specified character. For values of <code>ch</code> in the
1636 * range from 0 to 0xFFFF (inclusive), the index (in Unicode code
1637 * units) returned is the largest value <i>k</i> such that:
1639 * this.charAt(<i>k</i>) == ch
1640 * </pre></blockquote>
1641 * is true. For other values of <code>ch</code>, it is the
1642 * largest value <i>k</i> such that:
1644 * this.codePointAt(<i>k</i>) == ch
1645 * </pre></blockquote>
1646 * is true. In either case, if no such character occurs in this
1647 * string, then <code>-1</code> is returned. The
1648 * <code>String</code> is searched backwards starting at the last
1651 * @param ch a character (Unicode code point).
1652 * @return the index of the last occurrence of the character in the
1653 * character sequence represented by this object, or
1654 * <code>-1</code> if the character does not occur.
1656 public int lastIndexOf(int ch) {
1657 return lastIndexOf(ch, length() - 1);
1661 * Returns the index within this string of the last occurrence of
1662 * the specified character, searching backward starting at the
1663 * specified index. For values of <code>ch</code> in the range
1664 * from 0 to 0xFFFF (inclusive), the index returned is the largest
1665 * value <i>k</i> such that:
1667 * (this.charAt(<i>k</i>) == ch) && (<i>k</i> <= fromIndex)
1668 * </pre></blockquote>
1669 * is true. For other values of <code>ch</code>, it is the
1670 * largest value <i>k</i> such that:
1672 * (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> <= fromIndex)
1673 * </pre></blockquote>
1674 * is true. In either case, if no such character occurs in this
1675 * string at or before position <code>fromIndex</code>, then
1676 * <code>-1</code> is returned.
1678 * <p>All indices are specified in <code>char</code> values
1679 * (Unicode code units).
1681 * @param ch a character (Unicode code point).
1682 * @param fromIndex the index to start the search from. There is no
1683 * restriction on the value of <code>fromIndex</code>. If it is
1684 * greater than or equal to the length of this string, it has
1685 * the same effect as if it were equal to one less than the
1686 * length of this string: this entire string may be searched.
1687 * If it is negative, it has the same effect as if it were -1:
1689 * @return the index of the last occurrence of the character in the
1690 * character sequence represented by this object that is less
1691 * than or equal to <code>fromIndex</code>, or <code>-1</code>
1692 * if the character does not occur before that point.
1694 public int lastIndexOf(int ch, int fromIndex) {
1695 if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
1696 // handle most cases here (ch is a BMP code point or a
1697 // negative value (invalid code point))
1698 final char[] value = this.toCharArray();
1699 final int offset = this.offset();
1700 int i = offset + Math.min(fromIndex, length() - 1);
1701 for (; i >= offset ; i--) {
1702 if (value[i] == ch) {
1708 return lastIndexOfSupplementary(ch, fromIndex);
1713 * Handles (rare) calls of lastIndexOf with a supplementary character.
1715 private int lastIndexOfSupplementary(int ch, int fromIndex) {
1716 if (Character.isValidCodePoint(ch)) {
1717 final char[] value = this.toCharArray();
1718 final int offset = this.offset();
1719 char hi = Character.highSurrogate(ch);
1720 char lo = Character.lowSurrogate(ch);
1721 int i = offset + Math.min(fromIndex, length() - 2);
1722 for (; i >= offset; i--) {
1723 if (value[i] == hi && value[i+1] == lo) {
1732 * Returns the index within this string of the first occurrence of the
1733 * specified substring.
1735 * <p>The returned index is the smallest value <i>k</i> for which:
1737 * this.startsWith(str, <i>k</i>)
1738 * </pre></blockquote>
1739 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1741 * @param str the substring to search for.
1742 * @return the index of the first occurrence of the specified substring,
1743 * or {@code -1} if there is no such occurrence.
1745 public int indexOf(String str) {
1746 return indexOf(str, 0);
1750 * Returns the index within this string of the first occurrence of the
1751 * specified substring, starting at the specified index.
1753 * <p>The returned index is the smallest value <i>k</i> for which:
1755 * <i>k</i> >= fromIndex && this.startsWith(str, <i>k</i>)
1756 * </pre></blockquote>
1757 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1759 * @param str the substring to search for.
1760 * @param fromIndex the index from which to start the search.
1761 * @return the index of the first occurrence of the specified substring,
1762 * starting at the specified index,
1763 * or {@code -1} if there is no such occurrence.
1765 @JavaScriptBody(args = { "self", "str", "fromIndex" }, body =
1766 "return self.toString().indexOf(str.toString(), fromIndex) >= 0;"
1768 public int indexOf(String str, int fromIndex) {
1769 return indexOf(toCharArray(), offset(), length(), str.toCharArray(), str.offset(), str.length(), fromIndex);
1773 * Code shared by String and StringBuffer to do searches. The
1774 * source is the character array being searched, and the target
1775 * is the string being searched for.
1777 * @param source the characters being searched.
1778 * @param sourceOffset offset of the source string.
1779 * @param sourceCount count of the source string.
1780 * @param target the characters being searched for.
1781 * @param targetOffset offset of the target string.
1782 * @param targetCount count of the target string.
1783 * @param fromIndex the index to begin searching from.
1785 static int indexOf(char[] source, int sourceOffset, int sourceCount,
1786 char[] target, int targetOffset, int targetCount,
1788 if (fromIndex >= sourceCount) {
1789 return (targetCount == 0 ? sourceCount : -1);
1791 if (fromIndex < 0) {
1794 if (targetCount == 0) {
1798 char first = target[targetOffset];
1799 int max = sourceOffset + (sourceCount - targetCount);
1801 for (int i = sourceOffset + fromIndex; i <= max; i++) {
1802 /* Look for first character. */
1803 if (source[i] != first) {
1804 while (++i <= max && source[i] != first);
1807 /* Found first character, now look at the rest of v2 */
1810 int end = j + targetCount - 1;
1811 for (int k = targetOffset + 1; j < end && source[j] ==
1812 target[k]; j++, k++);
1815 /* Found whole string. */
1816 return i - sourceOffset;
1824 * Returns the index within this string of the last occurrence of the
1825 * specified substring. The last occurrence of the empty string ""
1826 * is considered to occur at the index value {@code this.length()}.
1828 * <p>The returned index is the largest value <i>k</i> for which:
1830 * this.startsWith(str, <i>k</i>)
1831 * </pre></blockquote>
1832 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1834 * @param str the substring to search for.
1835 * @return the index of the last occurrence of the specified substring,
1836 * or {@code -1} if there is no such occurrence.
1838 public int lastIndexOf(String str) {
1839 return lastIndexOf(str, length());
1843 * Returns the index within this string of the last occurrence of the
1844 * specified substring, searching backward starting at the specified index.
1846 * <p>The returned index is the largest value <i>k</i> for which:
1848 * <i>k</i> <= fromIndex && this.startsWith(str, <i>k</i>)
1849 * </pre></blockquote>
1850 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1852 * @param str the substring to search for.
1853 * @param fromIndex the index to start the search from.
1854 * @return the index of the last occurrence of the specified substring,
1855 * searching backward from the specified index,
1856 * or {@code -1} if there is no such occurrence.
1858 public int lastIndexOf(String str, int fromIndex) {
1859 return lastIndexOf(toCharArray(), offset(), length(), str.toCharArray(), str.offset(), str.length(), fromIndex);
1863 * Code shared by String and StringBuffer to do searches. The
1864 * source is the character array being searched, and the target
1865 * is the string being searched for.
1867 * @param source the characters being searched.
1868 * @param sourceOffset offset of the source string.
1869 * @param sourceCount count of the source string.
1870 * @param target the characters being searched for.
1871 * @param targetOffset offset of the target string.
1872 * @param targetCount count of the target string.
1873 * @param fromIndex the index to begin searching from.
1875 static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
1876 char[] target, int targetOffset, int targetCount,
1879 * Check arguments; return immediately where possible. For
1880 * consistency, don't check for null str.
1882 int rightIndex = sourceCount - targetCount;
1883 if (fromIndex < 0) {
1886 if (fromIndex > rightIndex) {
1887 fromIndex = rightIndex;
1889 /* Empty string always matches. */
1890 if (targetCount == 0) {
1894 int strLastIndex = targetOffset + targetCount - 1;
1895 char strLastChar = target[strLastIndex];
1896 int min = sourceOffset + targetCount - 1;
1897 int i = min + fromIndex;
1899 startSearchForLastChar:
1901 while (i >= min && source[i] != strLastChar) {
1908 int start = j - (targetCount - 1);
1909 int k = strLastIndex - 1;
1912 if (source[j--] != target[k--]) {
1914 continue startSearchForLastChar;
1917 return start - sourceOffset + 1;
1922 * Returns a new string that is a substring of this string. The
1923 * substring begins with the character at the specified index and
1924 * extends to the end of this string. <p>
1927 * "unhappy".substring(2) returns "happy"
1928 * "Harbison".substring(3) returns "bison"
1929 * "emptiness".substring(9) returns "" (an empty string)
1930 * </pre></blockquote>
1932 * @param beginIndex the beginning index, inclusive.
1933 * @return the specified substring.
1934 * @exception IndexOutOfBoundsException if
1935 * <code>beginIndex</code> is negative or larger than the
1936 * length of this <code>String</code> object.
1938 public String substring(int beginIndex) {
1939 return substring(beginIndex, length());
1943 * Returns a new string that is a substring of this string. The
1944 * substring begins at the specified <code>beginIndex</code> and
1945 * extends to the character at index <code>endIndex - 1</code>.
1946 * Thus the length of the substring is <code>endIndex-beginIndex</code>.
1950 * "hamburger".substring(4, 8) returns "urge"
1951 * "smiles".substring(1, 5) returns "mile"
1952 * </pre></blockquote>
1954 * @param beginIndex the beginning index, inclusive.
1955 * @param endIndex the ending index, exclusive.
1956 * @return the specified substring.
1957 * @exception IndexOutOfBoundsException if the
1958 * <code>beginIndex</code> is negative, or
1959 * <code>endIndex</code> is larger than the length of
1960 * this <code>String</code> object, or
1961 * <code>beginIndex</code> is larger than
1962 * <code>endIndex</code>.
1964 @JavaScriptBody(args = { "self", "beginIndex", "endIndex" }, body =
1965 "return self.toString().substring(beginIndex, endIndex);"
1967 public String substring(int beginIndex, int endIndex) {
1968 if (beginIndex < 0) {
1969 throw new StringIndexOutOfBoundsException(beginIndex);
1971 if (endIndex > length()) {
1972 throw new StringIndexOutOfBoundsException(endIndex);
1974 if (beginIndex > endIndex) {
1975 throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
1977 return ((beginIndex == 0) && (endIndex == length())) ? this :
1978 new String(toCharArray(), offset() + beginIndex, endIndex - beginIndex);
1982 * Returns a new character sequence that is a subsequence of this sequence.
1984 * <p> An invocation of this method of the form
1987 * str.subSequence(begin, end)</pre></blockquote>
1989 * behaves in exactly the same way as the invocation
1992 * str.substring(begin, end)</pre></blockquote>
1994 * This method is defined so that the <tt>String</tt> class can implement
1995 * the {@link CharSequence} interface. </p>
1997 * @param beginIndex the begin index, inclusive.
1998 * @param endIndex the end index, exclusive.
1999 * @return the specified subsequence.
2001 * @throws IndexOutOfBoundsException
2002 * if <tt>beginIndex</tt> or <tt>endIndex</tt> are negative,
2003 * if <tt>endIndex</tt> is greater than <tt>length()</tt>,
2004 * or if <tt>beginIndex</tt> is greater than <tt>startIndex</tt>
2009 public CharSequence subSequence(int beginIndex, int endIndex) {
2010 return this.substring(beginIndex, endIndex);
2014 * Concatenates the specified string to the end of this string.
2016 * If the length of the argument string is <code>0</code>, then this
2017 * <code>String</code> object is returned. Otherwise, a new
2018 * <code>String</code> object is created, representing a character
2019 * sequence that is the concatenation of the character sequence
2020 * represented by this <code>String</code> object and the character
2021 * sequence represented by the argument string.<p>
2024 * "cares".concat("s") returns "caress"
2025 * "to".concat("get").concat("her") returns "together"
2026 * </pre></blockquote>
2028 * @param str the <code>String</code> that is concatenated to the end
2029 * of this <code>String</code>.
2030 * @return a string that represents the concatenation of this object's
2031 * characters followed by the string argument's characters.
2033 public String concat(String str) {
2034 int otherLen = str.length();
2035 if (otherLen == 0) {
2038 char buf[] = new char[length() + otherLen];
2039 getChars(0, length(), buf, 0);
2040 str.getChars(0, otherLen, buf, length());
2041 return new String(buf, 0, length() + otherLen);
2045 * Returns a new string resulting from replacing all occurrences of
2046 * <code>oldChar</code> in this string with <code>newChar</code>.
2048 * If the character <code>oldChar</code> does not occur in the
2049 * character sequence represented by this <code>String</code> object,
2050 * then a reference to this <code>String</code> object is returned.
2051 * Otherwise, a new <code>String</code> object is created that
2052 * represents a character sequence identical to the character sequence
2053 * represented by this <code>String</code> object, except that every
2054 * occurrence of <code>oldChar</code> is replaced by an occurrence
2055 * of <code>newChar</code>.
2059 * "mesquite in your cellar".replace('e', 'o')
2060 * returns "mosquito in your collar"
2061 * "the war of baronets".replace('r', 'y')
2062 * returns "the way of bayonets"
2063 * "sparring with a purple porpoise".replace('p', 't')
2064 * returns "starring with a turtle tortoise"
2065 * "JonL".replace('q', 'x') returns "JonL" (no change)
2066 * </pre></blockquote>
2068 * @param oldChar the old character.
2069 * @param newChar the new character.
2070 * @return a string derived from this string by replacing every
2071 * occurrence of <code>oldChar</code> with <code>newChar</code>.
2073 @JavaScriptBody(args = { "self", "arg1", "arg2" }, body =
2074 "if (typeof arg1 === 'number') arg1 = String.fromCharCode(arg1);\n" +
2075 "if (typeof arg2 === 'number') arg2 = String.fromCharCode(arg2);\n" +
2076 "var s = self.toString();\n" +
2078 " var ret = s.replace(arg1, arg2);\n" +
2079 " if (ret === s) {\n" +
2085 public String replace(char oldChar, char newChar) {
2086 if (oldChar != newChar) {
2089 char[] val = toCharArray(); /* avoid getfield opcode */
2090 int off = offset(); /* avoid getfield opcode */
2093 if (val[off + i] == oldChar) {
2098 char buf[] = new char[len];
2099 for (int j = 0 ; j < i ; j++) {
2100 buf[j] = val[off+j];
2103 char c = val[off + i];
2104 buf[i] = (c == oldChar) ? newChar : c;
2107 return new String(buf, 0, len);
2114 * Tells whether or not this string matches the given <a
2115 * href="../util/regex/Pattern.html#sum">regular expression</a>.
2117 * <p> An invocation of this method of the form
2118 * <i>str</i><tt>.matches(</tt><i>regex</i><tt>)</tt> yields exactly the
2119 * same result as the expression
2121 * <blockquote><tt> {@link java.util.regex.Pattern}.{@link
2122 * java.util.regex.Pattern#matches(String,CharSequence)
2123 * matches}(</tt><i>regex</i><tt>,</tt> <i>str</i><tt>)</tt></blockquote>
2126 * the regular expression to which this string is to be matched
2128 * @return <tt>true</tt> if, and only if, this string matches the
2129 * given regular expression
2131 * @throws PatternSyntaxException
2132 * if the regular expression's syntax is invalid
2134 * @see java.util.regex.Pattern
2139 public boolean matches(String regex) {
2140 throw new UnsupportedOperationException();
2144 * Returns true if and only if this string contains the specified
2145 * sequence of char values.
2147 * @param s the sequence to search for
2148 * @return true if this string contains <code>s</code>, false otherwise
2149 * @throws NullPointerException if <code>s</code> is <code>null</code>
2152 public boolean contains(CharSequence s) {
2153 return indexOf(s.toString()) > -1;
2157 * Replaces the first substring of this string that matches the given <a
2158 * href="../util/regex/Pattern.html#sum">regular expression</a> with the
2159 * given replacement.
2161 * <p> An invocation of this method of the form
2162 * <i>str</i><tt>.replaceFirst(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt>
2163 * yields exactly the same result as the expression
2166 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2167 * compile}(</tt><i>regex</i><tt>).{@link
2168 * java.util.regex.Pattern#matcher(java.lang.CharSequence)
2169 * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceFirst
2170 * replaceFirst}(</tt><i>repl</i><tt>)</tt></blockquote>
2173 * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the
2174 * replacement string may cause the results to be different than if it were
2175 * being treated as a literal replacement string; see
2176 * {@link java.util.regex.Matcher#replaceFirst}.
2177 * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
2178 * meaning of these characters, if desired.
2181 * the regular expression to which this string is to be matched
2182 * @param replacement
2183 * the string to be substituted for the first match
2185 * @return The resulting <tt>String</tt>
2187 * @throws PatternSyntaxException
2188 * if the regular expression's syntax is invalid
2190 * @see java.util.regex.Pattern
2195 public String replaceFirst(String regex, String replacement) {
2196 throw new UnsupportedOperationException();
2200 * Replaces each substring of this string that matches the given <a
2201 * href="../util/regex/Pattern.html#sum">regular expression</a> with the
2202 * given replacement.
2204 * <p> An invocation of this method of the form
2205 * <i>str</i><tt>.replaceAll(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt>
2206 * yields exactly the same result as the expression
2209 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2210 * compile}(</tt><i>regex</i><tt>).{@link
2211 * java.util.regex.Pattern#matcher(java.lang.CharSequence)
2212 * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceAll
2213 * replaceAll}(</tt><i>repl</i><tt>)</tt></blockquote>
2216 * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the
2217 * replacement string may cause the results to be different than if it were
2218 * being treated as a literal replacement string; see
2219 * {@link java.util.regex.Matcher#replaceAll Matcher.replaceAll}.
2220 * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
2221 * meaning of these characters, if desired.
2224 * the regular expression to which this string is to be matched
2225 * @param replacement
2226 * the string to be substituted for each match
2228 * @return The resulting <tt>String</tt>
2230 * @throws PatternSyntaxException
2231 * if the regular expression's syntax is invalid
2233 * @see java.util.regex.Pattern
2238 public String replaceAll(String regex, String replacement) {
2239 throw new UnsupportedOperationException();
2243 * Replaces each substring of this string that matches the literal target
2244 * sequence with the specified literal replacement sequence. The
2245 * replacement proceeds from the beginning of the string to the end, for
2246 * example, replacing "aa" with "b" in the string "aaa" will result in
2247 * "ba" rather than "ab".
2249 * @param target The sequence of char values to be replaced
2250 * @param replacement The replacement sequence of char values
2251 * @return The resulting string
2252 * @throws NullPointerException if <code>target</code> or
2253 * <code>replacement</code> is <code>null</code>.
2256 public String replace(CharSequence target, CharSequence replacement) {
2257 throw new UnsupportedOperationException("This one should be supported, but without dep on rest of regexp");
2261 * Splits this string around matches of the given
2262 * <a href="../util/regex/Pattern.html#sum">regular expression</a>.
2264 * <p> The array returned by this method contains each substring of this
2265 * string that is terminated by another substring that matches the given
2266 * expression or is terminated by the end of the string. The substrings in
2267 * the array are in the order in which they occur in this string. If the
2268 * expression does not match any part of the input then the resulting array
2269 * has just one element, namely this string.
2271 * <p> The <tt>limit</tt> parameter controls the number of times the
2272 * pattern is applied and therefore affects the length of the resulting
2273 * array. If the limit <i>n</i> is greater than zero then the pattern
2274 * will be applied at most <i>n</i> - 1 times, the array's
2275 * length will be no greater than <i>n</i>, and the array's last entry
2276 * will contain all input beyond the last matched delimiter. If <i>n</i>
2277 * is non-positive then the pattern will be applied as many times as
2278 * possible and the array can have any length. If <i>n</i> is zero then
2279 * the pattern will be applied as many times as possible, the array can
2280 * have any length, and trailing empty strings will be discarded.
2282 * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the
2283 * following results with these parameters:
2285 * <blockquote><table cellpadding=1 cellspacing=0 summary="Split example showing regex, limit, and result">
2291 * <tr><td align=center>:</td>
2292 * <td align=center>2</td>
2293 * <td><tt>{ "boo", "and:foo" }</tt></td></tr>
2294 * <tr><td align=center>:</td>
2295 * <td align=center>5</td>
2296 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2297 * <tr><td align=center>:</td>
2298 * <td align=center>-2</td>
2299 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2300 * <tr><td align=center>o</td>
2301 * <td align=center>5</td>
2302 * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
2303 * <tr><td align=center>o</td>
2304 * <td align=center>-2</td>
2305 * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
2306 * <tr><td align=center>o</td>
2307 * <td align=center>0</td>
2308 * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
2309 * </table></blockquote>
2311 * <p> An invocation of this method of the form
2312 * <i>str.</i><tt>split(</tt><i>regex</i><tt>,</tt> <i>n</i><tt>)</tt>
2313 * yields the same result as the expression
2316 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2317 * compile}<tt>(</tt><i>regex</i><tt>)</tt>.{@link
2318 * java.util.regex.Pattern#split(java.lang.CharSequence,int)
2319 * split}<tt>(</tt><i>str</i><tt>,</tt> <i>n</i><tt>)</tt>
2324 * the delimiting regular expression
2327 * the result threshold, as described above
2329 * @return the array of strings computed by splitting this string
2330 * around matches of the given regular expression
2332 * @throws PatternSyntaxException
2333 * if the regular expression's syntax is invalid
2335 * @see java.util.regex.Pattern
2340 public String[] split(String regex, int limit) {
2341 throw new UnsupportedOperationException("Needs regexp");
2345 * Splits this string around matches of the given <a
2346 * href="../util/regex/Pattern.html#sum">regular expression</a>.
2348 * <p> This method works as if by invoking the two-argument {@link
2349 * #split(String, int) split} method with the given expression and a limit
2350 * argument of zero. Trailing empty strings are therefore not included in
2351 * the resulting array.
2353 * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the following
2354 * results with these expressions:
2356 * <blockquote><table cellpadding=1 cellspacing=0 summary="Split examples showing regex and result">
2361 * <tr><td align=center>:</td>
2362 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2363 * <tr><td align=center>o</td>
2364 * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
2365 * </table></blockquote>
2369 * the delimiting regular expression
2371 * @return the array of strings computed by splitting this string
2372 * around matches of the given regular expression
2374 * @throws PatternSyntaxException
2375 * if the regular expression's syntax is invalid
2377 * @see java.util.regex.Pattern
2382 public String[] split(String regex) {
2383 return split(regex, 0);
2387 * Converts all of the characters in this <code>String</code> to lower
2388 * case using the rules of the given <code>Locale</code>. Case mapping is based
2389 * on the Unicode Standard version specified by the {@link java.lang.Character Character}
2390 * class. Since case mappings are not always 1:1 char mappings, the resulting
2391 * <code>String</code> may be a different length than the original <code>String</code>.
2393 * Examples of lowercase mappings are in the following table:
2394 * <table border="1" summary="Lowercase mapping examples showing language code of locale, upper case, lower case, and description">
2396 * <th>Language Code of Locale</th>
2397 * <th>Upper Case</th>
2398 * <th>Lower Case</th>
2399 * <th>Description</th>
2402 * <td>tr (Turkish)</td>
2403 * <td>\u0130</td>
2404 * <td>\u0069</td>
2405 * <td>capital letter I with dot above -> small letter i</td>
2408 * <td>tr (Turkish)</td>
2409 * <td>\u0049</td>
2410 * <td>\u0131</td>
2411 * <td>capital letter I -> small letter dotless i </td>
2415 * <td>French Fries</td>
2416 * <td>french fries</td>
2417 * <td>lowercased all chars in String</td>
2421 * <td><img src="doc-files/capiota.gif" alt="capiota"><img src="doc-files/capchi.gif" alt="capchi">
2422 * <img src="doc-files/captheta.gif" alt="captheta"><img src="doc-files/capupsil.gif" alt="capupsil">
2423 * <img src="doc-files/capsigma.gif" alt="capsigma"></td>
2424 * <td><img src="doc-files/iota.gif" alt="iota"><img src="doc-files/chi.gif" alt="chi">
2425 * <img src="doc-files/theta.gif" alt="theta"><img src="doc-files/upsilon.gif" alt="upsilon">
2426 * <img src="doc-files/sigma1.gif" alt="sigma"></td>
2427 * <td>lowercased all chars in String</td>
2431 * @param locale use the case transformation rules for this locale
2432 * @return the <code>String</code>, converted to lowercase.
2433 * @see java.lang.String#toLowerCase()
2434 * @see java.lang.String#toUpperCase()
2435 * @see java.lang.String#toUpperCase(Locale)
2438 // public String toLowerCase(Locale locale) {
2439 // if (locale == null) {
2440 // throw new NullPointerException();
2445 // /* Now check if there are any characters that need to be changed. */
2447 // for (firstUpper = 0 ; firstUpper < count; ) {
2448 // char c = value[offset+firstUpper];
2449 // if ((c >= Character.MIN_HIGH_SURROGATE) &&
2450 // (c <= Character.MAX_HIGH_SURROGATE)) {
2451 // int supplChar = codePointAt(firstUpper);
2452 // if (supplChar != Character.toLowerCase(supplChar)) {
2455 // firstUpper += Character.charCount(supplChar);
2457 // if (c != Character.toLowerCase(c)) {
2466 // char[] result = new char[count];
2467 // int resultOffset = 0; /* result may grow, so i+resultOffset
2468 // * is the write location in result */
2470 // /* Just copy the first few lowerCase characters. */
2471 // arraycopy(value, offset, result, 0, firstUpper);
2473 // String lang = locale.getLanguage();
2474 // boolean localeDependent =
2475 // (lang == "tr" || lang == "az" || lang == "lt");
2476 // char[] lowerCharArray;
2480 // for (int i = firstUpper; i < count; i += srcCount) {
2481 // srcChar = (int)value[offset+i];
2482 // if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
2483 // (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
2484 // srcChar = codePointAt(i);
2485 // srcCount = Character.charCount(srcChar);
2489 // if (localeDependent || srcChar == '\u03A3') { // GREEK CAPITAL LETTER SIGMA
2490 // lowerChar = ConditionalSpecialCasing.toLowerCaseEx(this, i, locale);
2491 // } else if (srcChar == '\u0130') { // LATIN CAPITAL LETTER I DOT
2492 // lowerChar = Character.ERROR;
2494 // lowerChar = Character.toLowerCase(srcChar);
2496 // if ((lowerChar == Character.ERROR) ||
2497 // (lowerChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
2498 // if (lowerChar == Character.ERROR) {
2499 // if (!localeDependent && srcChar == '\u0130') {
2501 // ConditionalSpecialCasing.toLowerCaseCharArray(this, i, Locale.ENGLISH);
2504 // ConditionalSpecialCasing.toLowerCaseCharArray(this, i, locale);
2506 // } else if (srcCount == 2) {
2507 // resultOffset += Character.toChars(lowerChar, result, i + resultOffset) - srcCount;
2510 // lowerCharArray = Character.toChars(lowerChar);
2513 // /* Grow result if needed */
2514 // int mapLen = lowerCharArray.length;
2515 // if (mapLen > srcCount) {
2516 // char[] result2 = new char[result.length + mapLen - srcCount];
2517 // arraycopy(result, 0, result2, 0,
2518 // i + resultOffset);
2519 // result = result2;
2521 // for (int x=0; x<mapLen; ++x) {
2522 // result[i+resultOffset+x] = lowerCharArray[x];
2524 // resultOffset += (mapLen - srcCount);
2526 // result[i+resultOffset] = (char)lowerChar;
2529 // return new String(0, count+resultOffset, result);
2533 * Converts all of the characters in this <code>String</code> to lower
2534 * case using the rules of the default locale. This is equivalent to calling
2535 * <code>toLowerCase(Locale.getDefault())</code>.
2537 * <b>Note:</b> This method is locale sensitive, and may produce unexpected
2538 * results if used for strings that are intended to be interpreted locale
2540 * Examples are programming language identifiers, protocol keys, and HTML
2542 * For instance, <code>"TITLE".toLowerCase()</code> in a Turkish locale
2543 * returns <code>"t\u005Cu0131tle"</code>, where '\u005Cu0131' is the
2544 * LATIN SMALL LETTER DOTLESS I character.
2545 * To obtain correct results for locale insensitive strings, use
2546 * <code>toLowerCase(Locale.ENGLISH)</code>.
2548 * @return the <code>String</code>, converted to lowercase.
2549 * @see java.lang.String#toLowerCase(Locale)
2551 public String toLowerCase() {
2552 throw new UnsupportedOperationException("Should be supported but without connection to locale");
2556 * Converts all of the characters in this <code>String</code> to upper
2557 * case using the rules of the given <code>Locale</code>. Case mapping is based
2558 * on the Unicode Standard version specified by the {@link java.lang.Character Character}
2559 * class. Since case mappings are not always 1:1 char mappings, the resulting
2560 * <code>String</code> may be a different length than the original <code>String</code>.
2562 * Examples of locale-sensitive and 1:M case mappings are in the following table.
2564 * <table border="1" summary="Examples of locale-sensitive and 1:M case mappings. Shows Language code of locale, lower case, upper case, and description.">
2566 * <th>Language Code of Locale</th>
2567 * <th>Lower Case</th>
2568 * <th>Upper Case</th>
2569 * <th>Description</th>
2572 * <td>tr (Turkish)</td>
2573 * <td>\u0069</td>
2574 * <td>\u0130</td>
2575 * <td>small letter i -> capital letter I with dot above</td>
2578 * <td>tr (Turkish)</td>
2579 * <td>\u0131</td>
2580 * <td>\u0049</td>
2581 * <td>small letter dotless i -> capital letter I</td>
2585 * <td>\u00df</td>
2586 * <td>\u0053 \u0053</td>
2587 * <td>small letter sharp s -> two letters: SS</td>
2591 * <td>Fahrvergnügen</td>
2592 * <td>FAHRVERGNÜGEN</td>
2596 * @param locale use the case transformation rules for this locale
2597 * @return the <code>String</code>, converted to uppercase.
2598 * @see java.lang.String#toUpperCase()
2599 * @see java.lang.String#toLowerCase()
2600 * @see java.lang.String#toLowerCase(Locale)
2603 /* not for javascript
2604 public String toUpperCase(Locale locale) {
2605 if (locale == null) {
2606 throw new NullPointerException();
2611 // Now check if there are any characters that need to be changed.
2613 for (firstLower = 0 ; firstLower < count; ) {
2614 int c = (int)value[offset+firstLower];
2616 if ((c >= Character.MIN_HIGH_SURROGATE) &&
2617 (c <= Character.MAX_HIGH_SURROGATE)) {
2618 c = codePointAt(firstLower);
2619 srcCount = Character.charCount(c);
2623 int upperCaseChar = Character.toUpperCaseEx(c);
2624 if ((upperCaseChar == Character.ERROR) ||
2625 (c != upperCaseChar)) {
2628 firstLower += srcCount;
2633 char[] result = new char[count]; /* may grow *
2634 int resultOffset = 0; /* result may grow, so i+resultOffset
2635 * is the write location in result *
2637 /* Just copy the first few upperCase characters. *
2638 arraycopy(value, offset, result, 0, firstLower);
2640 String lang = locale.getLanguage();
2641 boolean localeDependent =
2642 (lang == "tr" || lang == "az" || lang == "lt");
2643 char[] upperCharArray;
2647 for (int i = firstLower; i < count; i += srcCount) {
2648 srcChar = (int)value[offset+i];
2649 if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
2650 (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
2651 srcChar = codePointAt(i);
2652 srcCount = Character.charCount(srcChar);
2656 if (localeDependent) {
2657 upperChar = ConditionalSpecialCasing.toUpperCaseEx(this, i, locale);
2659 upperChar = Character.toUpperCaseEx(srcChar);
2661 if ((upperChar == Character.ERROR) ||
2662 (upperChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
2663 if (upperChar == Character.ERROR) {
2664 if (localeDependent) {
2666 ConditionalSpecialCasing.toUpperCaseCharArray(this, i, locale);
2668 upperCharArray = Character.toUpperCaseCharArray(srcChar);
2670 } else if (srcCount == 2) {
2671 resultOffset += Character.toChars(upperChar, result, i + resultOffset) - srcCount;
2674 upperCharArray = Character.toChars(upperChar);
2677 /* Grow result if needed *
2678 int mapLen = upperCharArray.length;
2679 if (mapLen > srcCount) {
2680 char[] result2 = new char[result.length + mapLen - srcCount];
2681 arraycopy(result, 0, result2, 0,
2685 for (int x=0; x<mapLen; ++x) {
2686 result[i+resultOffset+x] = upperCharArray[x];
2688 resultOffset += (mapLen - srcCount);
2690 result[i+resultOffset] = (char)upperChar;
2693 return new String(0, count+resultOffset, result);
2698 * Converts all of the characters in this <code>String</code> to upper
2699 * case using the rules of the default locale. This method is equivalent to
2700 * <code>toUpperCase(Locale.getDefault())</code>.
2702 * <b>Note:</b> This method is locale sensitive, and may produce unexpected
2703 * results if used for strings that are intended to be interpreted locale
2705 * Examples are programming language identifiers, protocol keys, and HTML
2707 * For instance, <code>"title".toUpperCase()</code> in a Turkish locale
2708 * returns <code>"T\u005Cu0130TLE"</code>, where '\u005Cu0130' is the
2709 * LATIN CAPITAL LETTER I WITH DOT ABOVE character.
2710 * To obtain correct results for locale insensitive strings, use
2711 * <code>toUpperCase(Locale.ENGLISH)</code>.
2713 * @return the <code>String</code>, converted to uppercase.
2714 * @see java.lang.String#toUpperCase(Locale)
2716 public String toUpperCase() {
2717 throw new UnsupportedOperationException();
2721 * Returns a copy of the string, with leading and trailing whitespace
2724 * If this <code>String</code> object represents an empty character
2725 * sequence, or the first and last characters of character sequence
2726 * represented by this <code>String</code> object both have codes
2727 * greater than <code>'\u0020'</code> (the space character), then a
2728 * reference to this <code>String</code> object is returned.
2730 * Otherwise, if there is no character with a code greater than
2731 * <code>'\u0020'</code> in the string, then a new
2732 * <code>String</code> object representing an empty string is created
2735 * Otherwise, let <i>k</i> be the index of the first character in the
2736 * string whose code is greater than <code>'\u0020'</code>, and let
2737 * <i>m</i> be the index of the last character in the string whose code
2738 * is greater than <code>'\u0020'</code>. A new <code>String</code>
2739 * object is created, representing the substring of this string that
2740 * begins with the character at index <i>k</i> and ends with the
2741 * character at index <i>m</i>-that is, the result of
2742 * <code>this.substring(<i>k</i>, <i>m</i>+1)</code>.
2744 * This method may be used to trim whitespace (as defined above) from
2745 * the beginning and end of a string.
2747 * @return A copy of this string with leading and trailing white
2748 * space removed, or this string if it has no leading or
2749 * trailing white space.
2751 public String trim() {
2754 int off = offset(); /* avoid getfield opcode */
2755 char[] val = toCharArray(); /* avoid getfield opcode */
2757 while ((st < len) && (val[off + st] <= ' ')) {
2760 while ((st < len) && (val[off + len - 1] <= ' ')) {
2763 return ((st > 0) || (len < length())) ? substring(st, len) : this;
2767 * This object (which is already a string!) is itself returned.
2769 * @return the string itself.
2771 @JavaScriptBody(args = "self", body = "return self.toString();")
2772 public String toString() {
2777 * Converts this string to a new character array.
2779 * @return a newly allocated character array whose length is the length
2780 * of this string and whose contents are initialized to contain
2781 * the character sequence represented by this string.
2783 @JavaScriptBody(args = "self", body = "return self.toString().split('');")
2784 public char[] toCharArray() {
2785 char result[] = new char[length()];
2786 getChars(0, length(), result, 0);
2791 * Returns a formatted string using the specified format string and
2794 * <p> The locale always used is the one returned by {@link
2795 * java.util.Locale#getDefault() Locale.getDefault()}.
2798 * A <a href="../util/Formatter.html#syntax">format string</a>
2801 * Arguments referenced by the format specifiers in the format
2802 * string. If there are more arguments than format specifiers, the
2803 * extra arguments are ignored. The number of arguments is
2804 * variable and may be zero. The maximum number of arguments is
2805 * limited by the maximum dimension of a Java array as defined by
2806 * <cite>The Java™ Virtual Machine Specification</cite>.
2807 * The behaviour on a
2808 * <tt>null</tt> argument depends on the <a
2809 * href="../util/Formatter.html#syntax">conversion</a>.
2811 * @throws IllegalFormatException
2812 * If a format string contains an illegal syntax, a format
2813 * specifier that is incompatible with the given arguments,
2814 * insufficient arguments given the format string, or other
2815 * illegal conditions. For specification of all possible
2816 * formatting errors, see the <a
2817 * href="../util/Formatter.html#detail">Details</a> section of the
2818 * formatter class specification.
2820 * @throws NullPointerException
2821 * If the <tt>format</tt> is <tt>null</tt>
2823 * @return A formatted string
2825 * @see java.util.Formatter
2828 public static String format(String format, Object ... args) {
2829 throw new UnsupportedOperationException();
2833 * Returns a formatted string using the specified locale, format string,
2837 * The {@linkplain java.util.Locale locale} to apply during
2838 * formatting. If <tt>l</tt> is <tt>null</tt> then no localization
2842 * A <a href="../util/Formatter.html#syntax">format string</a>
2845 * Arguments referenced by the format specifiers in the format
2846 * string. If there are more arguments than format specifiers, the
2847 * extra arguments are ignored. The number of arguments is
2848 * variable and may be zero. The maximum number of arguments is
2849 * limited by the maximum dimension of a Java array as defined by
2850 * <cite>The Java™ Virtual Machine Specification</cite>.
2851 * The behaviour on a
2852 * <tt>null</tt> argument depends on the <a
2853 * href="../util/Formatter.html#syntax">conversion</a>.
2855 * @throws IllegalFormatException
2856 * If a format string contains an illegal syntax, a format
2857 * specifier that is incompatible with the given arguments,
2858 * insufficient arguments given the format string, or other
2859 * illegal conditions. For specification of all possible
2860 * formatting errors, see the <a
2861 * href="../util/Formatter.html#detail">Details</a> section of the
2862 * formatter class specification
2864 * @throws NullPointerException
2865 * If the <tt>format</tt> is <tt>null</tt>
2867 * @return A formatted string
2869 * @see java.util.Formatter
2872 // public static String format(Locale l, String format, Object ... args) {
2873 // return new Formatter(l).format(format, args).toString();
2877 * Returns the string representation of the <code>Object</code> argument.
2879 * @param obj an <code>Object</code>.
2880 * @return if the argument is <code>null</code>, then a string equal to
2881 * <code>"null"</code>; otherwise, the value of
2882 * <code>obj.toString()</code> is returned.
2883 * @see java.lang.Object#toString()
2885 public static String valueOf(Object obj) {
2886 return (obj == null) ? "null" : obj.toString();
2890 * Returns the string representation of the <code>char</code> array
2891 * argument. The contents of the character array are copied; subsequent
2892 * modification of the character array does not affect the newly
2895 * @param data a <code>char</code> array.
2896 * @return a newly allocated string representing the same sequence of
2897 * characters contained in the character array argument.
2899 public static String valueOf(char data[]) {
2900 return new String(data);
2904 * Returns the string representation of a specific subarray of the
2905 * <code>char</code> array argument.
2907 * The <code>offset</code> argument is the index of the first
2908 * character of the subarray. The <code>count</code> argument
2909 * specifies the length of the subarray. The contents of the subarray
2910 * are copied; subsequent modification of the character array does not
2911 * affect the newly created string.
2913 * @param data the character array.
2914 * @param offset the initial offset into the value of the
2915 * <code>String</code>.
2916 * @param count the length of the value of the <code>String</code>.
2917 * @return a string representing the sequence of characters contained
2918 * in the subarray of the character array argument.
2919 * @exception IndexOutOfBoundsException if <code>offset</code> is
2920 * negative, or <code>count</code> is negative, or
2921 * <code>offset+count</code> is larger than
2922 * <code>data.length</code>.
2924 public static String valueOf(char data[], int offset, int count) {
2925 return new String(data, offset, count);
2929 * Returns a String that represents the character sequence in the
2932 * @param data the character array.
2933 * @param offset initial offset of the subarray.
2934 * @param count length of the subarray.
2935 * @return a <code>String</code> that contains the characters of the
2936 * specified subarray of the character array.
2938 public static String copyValueOf(char data[], int offset, int count) {
2939 // All public String constructors now copy the data.
2940 return new String(data, offset, count);
2944 * Returns a String that represents the character sequence in the
2947 * @param data the character array.
2948 * @return a <code>String</code> that contains the characters of the
2951 public static String copyValueOf(char data[]) {
2952 return copyValueOf(data, 0, data.length);
2956 * Returns the string representation of the <code>boolean</code> argument.
2958 * @param b a <code>boolean</code>.
2959 * @return if the argument is <code>true</code>, a string equal to
2960 * <code>"true"</code> is returned; otherwise, a string equal to
2961 * <code>"false"</code> is returned.
2963 public static String valueOf(boolean b) {
2964 return b ? "true" : "false";
2968 * Returns the string representation of the <code>char</code>
2971 * @param c a <code>char</code>.
2972 * @return a string of length <code>1</code> containing
2973 * as its single character the argument <code>c</code>.
2975 public static String valueOf(char c) {
2977 return new String(data, 0, 1);
2981 * Returns the string representation of the <code>int</code> argument.
2983 * The representation is exactly the one returned by the
2984 * <code>Integer.toString</code> method of one argument.
2986 * @param i an <code>int</code>.
2987 * @return a string representation of the <code>int</code> argument.
2988 * @see java.lang.Integer#toString(int, int)
2990 public static String valueOf(int i) {
2991 return Integer.toString(i);
2995 * Returns the string representation of the <code>long</code> argument.
2997 * The representation is exactly the one returned by the
2998 * <code>Long.toString</code> method of one argument.
3000 * @param l a <code>long</code>.
3001 * @return a string representation of the <code>long</code> argument.
3002 * @see java.lang.Long#toString(long)
3004 public static String valueOf(long l) {
3005 return Long.toString(l);
3009 * Returns the string representation of the <code>float</code> argument.
3011 * The representation is exactly the one returned by the
3012 * <code>Float.toString</code> method of one argument.
3014 * @param f a <code>float</code>.
3015 * @return a string representation of the <code>float</code> argument.
3016 * @see java.lang.Float#toString(float)
3018 public static String valueOf(float f) {
3019 return Float.toString(f);
3023 * Returns the string representation of the <code>double</code> argument.
3025 * The representation is exactly the one returned by the
3026 * <code>Double.toString</code> method of one argument.
3028 * @param d a <code>double</code>.
3029 * @return a string representation of the <code>double</code> argument.
3030 * @see java.lang.Double#toString(double)
3032 public static String valueOf(double d) {
3033 return Double.toString(d);
3037 * Returns a canonical representation for the string object.
3039 * A pool of strings, initially empty, is maintained privately by the
3040 * class <code>String</code>.
3042 * When the intern method is invoked, if the pool already contains a
3043 * string equal to this <code>String</code> object as determined by
3044 * the {@link #equals(Object)} method, then the string from the pool is
3045 * returned. Otherwise, this <code>String</code> object is added to the
3046 * pool and a reference to this <code>String</code> object is returned.
3048 * It follows that for any two strings <code>s</code> and <code>t</code>,
3049 * <code>s.intern() == t.intern()</code> is <code>true</code>
3050 * if and only if <code>s.equals(t)</code> is <code>true</code>.
3052 * All literal strings and string-valued constant expressions are
3053 * interned. String literals are defined in section 3.10.5 of the
3054 * <cite>The Java™ Language Specification</cite>.
3056 * @return a string that has the same contents as this string, but is
3057 * guaranteed to be from a pool of unique strings.
3059 public native String intern();