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
111 /** real string to delegate to */
114 /** use serialVersionUID from JDK 1.0.2 for interoperability */
115 private static final long serialVersionUID = -6849794470754667710L;
117 @JavaScriptOnly(name="toString", value="function() { return this.fld_r; }")
118 private static void jsToString() {
121 @JavaScriptOnly(name="valueOf", value="function() { return this.toString().valueOf(); }")
122 private static void jsValudOf() {
126 * Class String is special cased within the Serialization Stream Protocol.
128 * A String instance is written initially into an ObjectOutputStream in the
131 * <code>TC_STRING</code> (utf String)
133 * The String is written by method <code>DataOutput.writeUTF</code>.
134 * A new handle is generated to refer to all future references to the
135 * string instance within the stream.
137 // private static final ObjectStreamField[] serialPersistentFields =
138 // new ObjectStreamField[0];
141 * Initializes a newly created {@code String} object so that it represents
142 * an empty character sequence. Note that use of this constructor is
143 * unnecessary since Strings are immutable.
150 * Initializes a newly created {@code String} object so that it represents
151 * the same sequence of characters as the argument; in other words, the
152 * newly created string is a copy of the argument string. Unless an
153 * explicit copy of {@code original} is needed, use of this constructor is
154 * unnecessary since Strings are immutable.
159 public String(String original) {
160 this.r = original.toString();
164 * Allocates a new {@code String} so that it represents the sequence of
165 * characters currently contained in the character array argument. The
166 * contents of the character array are copied; subsequent modification of
167 * the character array does not affect the newly created string.
170 * The initial value of the string
172 @JavaScriptBody(args = { "charArr" }, body=
173 "for (var i = 0; i < charArr.length; i++) {\n"
174 + " if (typeof charArr[i] === 'number') charArr[i] = String.fromCharCode(charArr[i]);\n"
176 + "this.fld_r = charArr.join('');\n"
178 public String(char value[]) {
182 * Allocates a new {@code String} that contains characters from a subarray
183 * of the character array argument. The {@code offset} argument is the
184 * index of the first character of the subarray and the {@code count}
185 * argument specifies the length of the subarray. The contents of the
186 * subarray are copied; subsequent modification of the character array does
187 * not affect the newly created string.
190 * Array that is the source of characters
198 * @throws IndexOutOfBoundsException
199 * If the {@code offset} and {@code count} arguments index
200 * characters outside the bounds of the {@code value} array
202 @JavaScriptBody(args = { "charArr", "off", "cnt" }, body =
203 "var up = off + cnt;\n" +
204 "for (var i = off; i < up; i++) {\n" +
205 " if (typeof charArr[i] === 'number') charArr[i] = String.fromCharCode(charArr[i]);\n" +
207 "this.fld_r = charArr.slice(off, up).join(\"\");\n"
209 public String(char value[], int offset, int count) {
213 * Allocates a new {@code String} that contains characters from a subarray
214 * of the <a href="Character.html#unicode">Unicode code point</a> array
215 * argument. The {@code offset} argument is the index of the first code
216 * point of the subarray and the {@code count} argument specifies the
217 * length of the subarray. The contents of the subarray are converted to
218 * {@code char}s; subsequent modification of the {@code int} array does not
219 * affect the newly created string.
222 * Array that is the source of Unicode code points
230 * @throws IllegalArgumentException
231 * If any invalid Unicode code point is found in {@code
234 * @throws IndexOutOfBoundsException
235 * If the {@code offset} and {@code count} arguments index
236 * characters outside the bounds of the {@code codePoints} array
240 public String(int[] codePoints, int offset, int count) {
242 throw new StringIndexOutOfBoundsException(offset);
245 throw new StringIndexOutOfBoundsException(count);
247 // Note: offset or count might be near -1>>>1.
248 if (offset > codePoints.length - count) {
249 throw new StringIndexOutOfBoundsException(offset + count);
252 final int end = offset + count;
254 // Pass 1: Compute precise size of char[]
256 for (int i = offset; i < end; i++) {
257 int c = codePoints[i];
258 if (Character.isBmpCodePoint(c))
260 else if (Character.isValidCodePoint(c))
262 else throw new IllegalArgumentException(Integer.toString(c));
265 // Pass 2: Allocate and fill in char[]
266 final char[] v = new char[n];
268 for (int i = offset, j = 0; i < end; i++, j++) {
269 int c = codePoints[i];
270 if (Character.isBmpCodePoint(c))
273 Character.toSurrogates(c, v, j++);
276 this.r = new String(v, 0, n);
280 * Allocates a new {@code String} constructed from a subarray of an array
281 * of 8-bit integer values.
283 * <p> The {@code offset} argument is the index of the first byte of the
284 * subarray, and the {@code count} argument specifies the length of the
287 * <p> Each {@code byte} in the subarray is converted to a {@code char} as
288 * specified in the method above.
290 * @deprecated This method does not properly convert bytes into characters.
291 * As of JDK 1.1, the preferred way to do this is via the
292 * {@code String} constructors that take a {@link
293 * java.nio.charset.Charset}, charset name, or that use the platform's
297 * The bytes to be converted to characters
300 * The top 8 bits of each 16-bit Unicode code unit
307 * @throws IndexOutOfBoundsException
308 * If the {@code offset} or {@code count} argument is invalid
310 * @see #String(byte[], int)
311 * @see #String(byte[], int, int, java.lang.String)
312 * @see #String(byte[], int, int, java.nio.charset.Charset)
313 * @see #String(byte[], int, int)
314 * @see #String(byte[], java.lang.String)
315 * @see #String(byte[], java.nio.charset.Charset)
316 * @see #String(byte[])
319 public String(byte ascii[], int hibyte, int offset, int count) {
320 checkBounds(ascii, offset, count);
321 char value[] = new char[count];
324 for (int i = count ; i-- > 0 ;) {
325 value[i] = (char) (ascii[i + offset] & 0xff);
329 for (int i = count ; i-- > 0 ;) {
330 value[i] = (char) (hibyte | (ascii[i + offset] & 0xff));
333 this.r = new String(value, 0, count);
337 * Allocates a new {@code String} containing characters constructed from
338 * an array of 8-bit integer values. Each character <i>c</i>in the
339 * resulting string is constructed from the corresponding component
340 * <i>b</i> in the byte array such that:
343 * <b><i>c</i></b> == (char)(((hibyte & 0xff) << 8)
344 * | (<b><i>b</i></b> & 0xff))
345 * </pre></blockquote>
347 * @deprecated This method does not properly convert bytes into
348 * characters. As of JDK 1.1, the preferred way to do this is via the
349 * {@code String} constructors that take a {@link
350 * java.nio.charset.Charset}, charset name, or that use the platform's
354 * The bytes to be converted to characters
357 * The top 8 bits of each 16-bit Unicode code unit
359 * @see #String(byte[], int, int, java.lang.String)
360 * @see #String(byte[], int, int, java.nio.charset.Charset)
361 * @see #String(byte[], int, int)
362 * @see #String(byte[], java.lang.String)
363 * @see #String(byte[], java.nio.charset.Charset)
364 * @see #String(byte[])
367 public String(byte ascii[], int hibyte) {
368 this(ascii, hibyte, 0, ascii.length);
371 /* Common private utility method used to bounds check the byte array
372 * and requested offset & length values used by the String(byte[],..)
375 private static void checkBounds(byte[] bytes, int offset, int length) {
377 throw new StringIndexOutOfBoundsException(length);
379 throw new StringIndexOutOfBoundsException(offset);
380 if (offset > bytes.length - length)
381 throw new StringIndexOutOfBoundsException(offset + length);
385 * Constructs a new {@code String} by decoding the specified subarray of
386 * bytes using the specified charset. The length of the new {@code String}
387 * is a function of the charset, and hence may not be equal to the length
390 * <p> The behavior of this constructor when the given bytes are not valid
391 * in the given charset is unspecified. The {@link
392 * java.nio.charset.CharsetDecoder} class should be used when more control
393 * over the decoding process is required.
396 * The bytes to be decoded into characters
399 * The index of the first byte to decode
402 * The number of bytes to decode
405 * The name of a supported {@linkplain java.nio.charset.Charset
408 * @throws UnsupportedEncodingException
409 * If the named charset is not supported
411 * @throws IndexOutOfBoundsException
412 * If the {@code offset} and {@code length} arguments index
413 * characters outside the bounds of the {@code bytes} array
417 // public String(byte bytes[], int offset, int length, String charsetName)
418 // throws UnsupportedEncodingException
420 // if (charsetName == null)
421 // throw new NullPointerException("charsetName");
422 // checkBounds(bytes, offset, length);
423 // char[] v = StringCoding.decode(charsetName, bytes, offset, length);
425 // this.count = v.length;
430 * Constructs a new {@code String} by decoding the specified subarray of
431 * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
432 * The length of the new {@code String} is a function of the charset, and
433 * hence may not be equal to the length of the subarray.
435 * <p> This method always replaces malformed-input and unmappable-character
436 * sequences with this charset's default replacement string. The {@link
437 * java.nio.charset.CharsetDecoder} class should be used when more control
438 * over the decoding process is required.
441 * The bytes to be decoded into characters
444 * The index of the first byte to decode
447 * The number of bytes to decode
450 * The {@linkplain java.nio.charset.Charset charset} to be used to
451 * decode the {@code bytes}
453 * @throws IndexOutOfBoundsException
454 * If the {@code offset} and {@code length} arguments index
455 * characters outside the bounds of the {@code bytes} array
459 /* don't want dependnecy on Charset
460 public String(byte bytes[], int offset, int length, Charset charset) {
462 throw new NullPointerException("charset");
463 checkBounds(bytes, offset, length);
464 char[] v = StringCoding.decode(charset, bytes, offset, length);
466 this.count = v.length;
472 * Constructs a new {@code String} by decoding the specified array of bytes
473 * using the specified {@linkplain java.nio.charset.Charset charset}. The
474 * length of the new {@code String} is a function of the charset, and hence
475 * may not be equal to the length of the byte array.
477 * <p> The behavior of this constructor when the given bytes are not valid
478 * in the given charset is unspecified. The {@link
479 * java.nio.charset.CharsetDecoder} class should be used when more control
480 * over the decoding process is required.
483 * The bytes to be decoded into characters
486 * The name of a supported {@linkplain java.nio.charset.Charset
489 * @throws UnsupportedEncodingException
490 * If the named charset is not supported
494 // public String(byte bytes[], String charsetName)
495 // throws UnsupportedEncodingException
497 // this(bytes, 0, bytes.length, charsetName);
501 * Constructs a new {@code String} by decoding the specified array of
502 * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
503 * The length of the new {@code String} is a function of the charset, and
504 * hence may not be equal to the length of the byte array.
506 * <p> This method always replaces malformed-input and unmappable-character
507 * sequences with this charset's default replacement string. The {@link
508 * java.nio.charset.CharsetDecoder} class should be used when more control
509 * over the decoding process is required.
512 * The bytes to be decoded into characters
515 * The {@linkplain java.nio.charset.Charset charset} to be used to
516 * decode the {@code bytes}
520 /* don't want dep on Charset
521 public String(byte bytes[], Charset charset) {
522 this(bytes, 0, bytes.length, charset);
527 * Constructs a new {@code String} by decoding the specified subarray of
528 * bytes using the platform's default charset. The length of the new
529 * {@code String} is a function of the charset, and hence may not be equal
530 * to the length of the subarray.
532 * <p> The behavior of this constructor when the given bytes are not valid
533 * in the default charset is unspecified. The {@link
534 * java.nio.charset.CharsetDecoder} class should be used when more control
535 * over the decoding process is required.
538 * The bytes to be decoded into characters
541 * The index of the first byte to decode
544 * The number of bytes to decode
546 * @throws IndexOutOfBoundsException
547 * If the {@code offset} and the {@code length} arguments index
548 * characters outside the bounds of the {@code bytes} array
552 public String(byte bytes[], int offset, int length) {
553 checkBounds(bytes, offset, length);
554 char[] v = new char[length];
555 for (int i = 0; i < length; i++) {
556 v[i] = (char)bytes[offset++];
558 this.r = new String(v, 0, v.length);
562 * Constructs a new {@code String} by decoding the specified array of bytes
563 * using the platform's default charset. The length of the new {@code
564 * String} is a function of the charset, and hence may not be equal to the
565 * length of the byte array.
567 * <p> The behavior of this constructor when the given bytes are not valid
568 * in the default charset is unspecified. The {@link
569 * java.nio.charset.CharsetDecoder} class should be used when more control
570 * over the decoding process is required.
573 * The bytes to be decoded into characters
577 public String(byte bytes[]) {
578 this(bytes, 0, bytes.length);
582 * Allocates a new string that contains the sequence of characters
583 * currently contained in the string buffer argument. The contents of the
584 * string buffer are copied; subsequent modification of the string buffer
585 * does not affect the newly created string.
588 * A {@code StringBuffer}
590 public String(StringBuffer buffer) {
591 this.r = buffer.toString();
595 * Allocates a new string that contains the sequence of characters
596 * currently contained in the string builder argument. The contents of the
597 * string builder are copied; subsequent modification of the string builder
598 * does not affect the newly created string.
600 * <p> This constructor is provided to ease migration to {@code
601 * StringBuilder}. Obtaining a string from a string builder via the {@code
602 * toString} method is likely to run faster and is generally preferred.
605 * A {@code StringBuilder}
609 public String(StringBuilder builder) {
610 this.r = builder.toString();
614 * Returns the length of this string.
615 * The length is equal to the number of <a href="Character.html#unicode">Unicode
616 * code units</a> in the string.
618 * @return the length of the sequence of characters represented by this
621 @JavaScriptBody(args = {}, body = "return this.toString().length;")
622 public int length() {
623 throw new UnsupportedOperationException();
627 * Returns <tt>true</tt> if, and only if, {@link #length()} is <tt>0</tt>.
629 * @return <tt>true</tt> if {@link #length()} is <tt>0</tt>, otherwise
634 @JavaScriptBody(args = {}, body="return this.toString().length === 0;")
635 public boolean isEmpty() {
636 return length() == 0;
640 * Returns the <code>char</code> value at the
641 * specified index. An index ranges from <code>0</code> to
642 * <code>length() - 1</code>. The first <code>char</code> value of the sequence
643 * is at index <code>0</code>, the next at index <code>1</code>,
644 * and so on, as for array indexing.
646 * <p>If the <code>char</code> value specified by the index is a
647 * <a href="Character.html#unicode">surrogate</a>, the surrogate
650 * @param index the index of the <code>char</code> value.
651 * @return the <code>char</code> value at the specified index of this string.
652 * The first <code>char</code> value is at index <code>0</code>.
653 * @exception IndexOutOfBoundsException if the <code>index</code>
654 * argument is negative or not less than the length of this
657 @JavaScriptBody(args = { "index" },
658 body = "return this.toString().charCodeAt(index);"
660 public char charAt(int index) {
661 throw new UnsupportedOperationException();
665 * Returns the character (Unicode code point) at the specified
666 * index. The index refers to <code>char</code> values
667 * (Unicode code units) and ranges from <code>0</code> to
668 * {@link #length()}<code> - 1</code>.
670 * <p> If the <code>char</code> value specified at the given index
671 * is in the high-surrogate range, the following index is less
672 * than the length of this <code>String</code>, and the
673 * <code>char</code> value at the following index is in the
674 * low-surrogate range, then the supplementary code point
675 * corresponding to this surrogate pair is returned. Otherwise,
676 * the <code>char</code> value at the given index is returned.
678 * @param index the index to the <code>char</code> values
679 * @return the code point value of the character at the
681 * @exception IndexOutOfBoundsException if the <code>index</code>
682 * argument is negative or not less than the length of this
686 public int codePointAt(int index) {
687 if ((index < 0) || (index >= length())) {
688 throw new StringIndexOutOfBoundsException(index);
690 return Character.codePointAtImpl(toCharArray(), offset() + index, offset() + length());
694 * Returns the character (Unicode code point) before the specified
695 * index. The index refers to <code>char</code> values
696 * (Unicode code units) and ranges from <code>1</code> to {@link
697 * CharSequence#length() length}.
699 * <p> If the <code>char</code> value at <code>(index - 1)</code>
700 * is in the low-surrogate range, <code>(index - 2)</code> is not
701 * negative, and the <code>char</code> value at <code>(index -
702 * 2)</code> is in the high-surrogate range, then the
703 * supplementary code point value of the surrogate pair is
704 * returned. If the <code>char</code> value at <code>index -
705 * 1</code> is an unpaired low-surrogate or a high-surrogate, the
706 * surrogate value is returned.
708 * @param index the index following the code point that should be returned
709 * @return the Unicode code point value before the given index.
710 * @exception IndexOutOfBoundsException if the <code>index</code>
711 * argument is less than 1 or greater than the length
715 public int codePointBefore(int index) {
717 if ((i < 0) || (i >= length())) {
718 throw new StringIndexOutOfBoundsException(index);
720 return Character.codePointBeforeImpl(toCharArray(), offset() + index, offset());
724 * Returns the number of Unicode code points in the specified text
725 * range of this <code>String</code>. The text range begins at the
726 * specified <code>beginIndex</code> and extends to the
727 * <code>char</code> at index <code>endIndex - 1</code>. Thus the
728 * length (in <code>char</code>s) of the text range is
729 * <code>endIndex-beginIndex</code>. Unpaired surrogates within
730 * the text range count as one code point each.
732 * @param beginIndex the index to the first <code>char</code> of
734 * @param endIndex the index after the last <code>char</code> of
736 * @return the number of Unicode code points in the specified text
738 * @exception IndexOutOfBoundsException if the
739 * <code>beginIndex</code> is negative, or <code>endIndex</code>
740 * is larger than the length of this <code>String</code>, or
741 * <code>beginIndex</code> is larger than <code>endIndex</code>.
744 public int codePointCount(int beginIndex, int endIndex) {
745 if (beginIndex < 0 || endIndex > length() || beginIndex > endIndex) {
746 throw new IndexOutOfBoundsException();
748 return Character.codePointCountImpl(toCharArray(), offset()+beginIndex, endIndex-beginIndex);
752 * Returns the index within this <code>String</code> that is
753 * offset from the given <code>index</code> by
754 * <code>codePointOffset</code> code points. Unpaired surrogates
755 * within the text range given by <code>index</code> and
756 * <code>codePointOffset</code> count as one code point each.
758 * @param index the index to be offset
759 * @param codePointOffset the offset in code points
760 * @return the index within this <code>String</code>
761 * @exception IndexOutOfBoundsException if <code>index</code>
762 * is negative or larger then the length of this
763 * <code>String</code>, or if <code>codePointOffset</code> is positive
764 * and the substring starting with <code>index</code> has fewer
765 * than <code>codePointOffset</code> code points,
766 * or if <code>codePointOffset</code> is negative and the substring
767 * before <code>index</code> has fewer than the absolute value
768 * of <code>codePointOffset</code> code points.
771 public int offsetByCodePoints(int index, int codePointOffset) {
772 if (index < 0 || index > length()) {
773 throw new IndexOutOfBoundsException();
775 return Character.offsetByCodePointsImpl(toCharArray(), offset(), length(),
776 offset()+index, codePointOffset) - offset();
780 * Copy characters from this string into dst starting at dstBegin.
781 * This method doesn't perform any range checking.
783 @JavaScriptBody(args = { "arr", "to" }, body =
784 "var s = this.toString();\n" +
785 "for (var i = 0; i < s.length; i++) {\n" +
786 " arr[to++] = s[i];\n" +
789 void getChars(char dst[], int dstBegin) {
790 AbstractStringBuilder.arraycopy(toCharArray(), offset(), dst, dstBegin, length());
794 * Copies characters from this string into the destination character
797 * The first character to be copied is at index <code>srcBegin</code>;
798 * the last character to be copied is at index <code>srcEnd-1</code>
799 * (thus the total number of characters to be copied is
800 * <code>srcEnd-srcBegin</code>). The characters are copied into the
801 * subarray of <code>dst</code> starting at index <code>dstBegin</code>
802 * and ending at index:
803 * <p><blockquote><pre>
804 * dstbegin + (srcEnd-srcBegin) - 1
805 * </pre></blockquote>
807 * @param srcBegin index of the first character in the string
809 * @param srcEnd index after the last character in the string
811 * @param dst the destination array.
812 * @param dstBegin the start offset in the destination array.
813 * @exception IndexOutOfBoundsException If any of the following
815 * <ul><li><code>srcBegin</code> is negative.
816 * <li><code>srcBegin</code> is greater than <code>srcEnd</code>
817 * <li><code>srcEnd</code> is greater than the length of this
819 * <li><code>dstBegin</code> is negative
820 * <li><code>dstBegin+(srcEnd-srcBegin)</code> is larger than
821 * <code>dst.length</code></ul>
823 @JavaScriptBody(args = { "beg", "end", "arr", "dst" }, body=
824 "var s = this.toString();\n" +
825 "while (beg < end) {\n" +
826 " arr[dst++] = s[beg++];\n" +
829 public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
831 throw new StringIndexOutOfBoundsException(srcBegin);
833 if (srcEnd > length()) {
834 throw new StringIndexOutOfBoundsException(srcEnd);
836 if (srcBegin > srcEnd) {
837 throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
839 AbstractStringBuilder.arraycopy(toCharArray(), offset() + srcBegin, dst, dstBegin,
844 * Copies characters from this string into the destination byte array. Each
845 * byte receives the 8 low-order bits of the corresponding character. The
846 * eight high-order bits of each character are not copied and do not
847 * participate in the transfer in any way.
849 * <p> The first character to be copied is at index {@code srcBegin}; the
850 * last character to be copied is at index {@code srcEnd-1}. The total
851 * number of characters to be copied is {@code srcEnd-srcBegin}. The
852 * characters, converted to bytes, are copied into the subarray of {@code
853 * dst} starting at index {@code dstBegin} and ending at index:
856 * dstbegin + (srcEnd-srcBegin) - 1
857 * </pre></blockquote>
859 * @deprecated This method does not properly convert characters into
860 * bytes. As of JDK 1.1, the preferred way to do this is via the
861 * {@link #getBytes()} method, which uses the platform's default charset.
864 * Index of the first character in the string to copy
867 * Index after the last character in the string to copy
870 * The destination array
873 * The start offset in the destination array
875 * @throws IndexOutOfBoundsException
876 * If any of the following is true:
878 * <li> {@code srcBegin} is negative
879 * <li> {@code srcBegin} is greater than {@code srcEnd}
880 * <li> {@code srcEnd} is greater than the length of this String
881 * <li> {@code dstBegin} is negative
882 * <li> {@code dstBegin+(srcEnd-srcBegin)} is larger than {@code
887 public void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin) {
889 throw new StringIndexOutOfBoundsException(srcBegin);
891 if (srcEnd > length()) {
892 throw new StringIndexOutOfBoundsException(srcEnd);
894 if (srcBegin > srcEnd) {
895 throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
898 int n = offset() + srcEnd;
899 int i = offset() + srcBegin;
900 char[] val = toCharArray(); /* avoid getfield opcode */
903 dst[j++] = (byte)val[i++];
908 * Encodes this {@code String} into a sequence of bytes using the named
909 * charset, storing the result into a new byte array.
911 * <p> The behavior of this method when this string cannot be encoded in
912 * the given charset is unspecified. The {@link
913 * java.nio.charset.CharsetEncoder} class should be used when more control
914 * over the encoding process is required.
917 * The name of a supported {@linkplain java.nio.charset.Charset
920 * @return The resultant byte array
922 * @throws UnsupportedEncodingException
923 * If the named charset is not supported
927 // public byte[] getBytes(String charsetName)
928 // throws UnsupportedEncodingException
930 // if (charsetName == null) throw new NullPointerException();
931 // return StringCoding.encode(charsetName, value, offset, count);
935 * Encodes this {@code String} into a sequence of bytes using the given
936 * {@linkplain java.nio.charset.Charset charset}, storing the result into a
939 * <p> This method always replaces malformed-input and unmappable-character
940 * sequences with this charset's default replacement byte array. The
941 * {@link java.nio.charset.CharsetEncoder} class should be used when more
942 * control over the encoding process is required.
945 * The {@linkplain java.nio.charset.Charset} to be used to encode
948 * @return The resultant byte array
952 /* don't want dep on Charset
953 public byte[] getBytes(Charset charset) {
954 if (charset == null) throw new NullPointerException();
955 return StringCoding.encode(charset, value, offset, count);
960 * Encodes this {@code String} into a sequence of bytes using the
961 * platform's default charset, storing the result into a new byte array.
963 * <p> The behavior of this method when this string cannot be encoded in
964 * the default charset is unspecified. The {@link
965 * java.nio.charset.CharsetEncoder} class should be used when more control
966 * over the encoding process is required.
968 * @return The resultant byte array
972 public byte[] getBytes() {
973 byte[] arr = new byte[length()];
974 for (int i = 0; i < arr.length; i++) {
975 final char v = charAt(i);
982 * Compares this string to the specified object. The result is {@code
983 * true} if and only if the argument is not {@code null} and is a {@code
984 * String} object that represents the same sequence of characters as this
988 * The object to compare this {@code String} against
990 * @return {@code true} if the given object represents a {@code String}
991 * equivalent to this string, {@code false} otherwise
993 * @see #compareTo(String)
994 * @see #equalsIgnoreCase(String)
996 @JavaScriptBody(args = { "obj" }, body =
997 "return obj != null && obj.$instOf_java_lang_String && "
998 + "this.toString() === obj.toString();"
1000 public boolean equals(Object anObject) {
1001 if (this == anObject) {
1004 if (anObject instanceof String) {
1005 String anotherString = (String)anObject;
1007 if (n == anotherString.length()) {
1008 char v1[] = toCharArray();
1009 char v2[] = anotherString.toCharArray();
1011 int j = anotherString.offset();
1013 if (v1[i++] != v2[j++])
1023 * Compares this string to the specified {@code StringBuffer}. The result
1024 * is {@code true} if and only if this {@code String} represents the same
1025 * sequence of characters as the specified {@code StringBuffer}.
1028 * The {@code StringBuffer} to compare this {@code String} against
1030 * @return {@code true} if this {@code String} represents the same
1031 * sequence of characters as the specified {@code StringBuffer},
1032 * {@code false} otherwise
1036 public boolean contentEquals(StringBuffer sb) {
1038 return contentEquals((CharSequence)sb);
1043 * Compares this string to the specified {@code CharSequence}. The result
1044 * is {@code true} if and only if this {@code String} represents the same
1045 * sequence of char values as the specified sequence.
1048 * The sequence to compare this {@code String} against
1050 * @return {@code true} if this {@code String} represents the same
1051 * sequence of char values as the specified sequence, {@code
1056 public boolean contentEquals(CharSequence cs) {
1057 if (length() != cs.length())
1059 // Argument is a StringBuffer, StringBuilder
1060 if (cs instanceof AbstractStringBuilder) {
1061 char v1[] = toCharArray();
1062 char v2[] = ((AbstractStringBuilder)cs).getValue();
1067 if (v1[i++] != v2[j++])
1072 // Argument is a String
1073 if (cs.equals(this))
1075 // Argument is a generic CharSequence
1076 char v1[] = toCharArray();
1081 if (v1[i++] != cs.charAt(j++))
1088 * Compares this {@code String} to another {@code String}, ignoring case
1089 * considerations. Two strings are considered equal ignoring case if they
1090 * are of the same length and corresponding characters in the two strings
1091 * are equal ignoring case.
1093 * <p> Two characters {@code c1} and {@code c2} are considered the same
1094 * ignoring case if at least one of the following is true:
1096 * <li> The two characters are the same (as compared by the
1097 * {@code ==} operator)
1098 * <li> Applying the method {@link
1099 * java.lang.Character#toUpperCase(char)} to each character
1100 * produces the same result
1101 * <li> Applying the method {@link
1102 * java.lang.Character#toLowerCase(char)} to each character
1103 * produces the same result
1106 * @param anotherString
1107 * The {@code String} to compare this {@code String} against
1109 * @return {@code true} if the argument is not {@code null} and it
1110 * represents an equivalent {@code String} ignoring case; {@code
1113 * @see #equals(Object)
1115 public boolean equalsIgnoreCase(String anotherString) {
1116 return (this == anotherString) ? true :
1117 (anotherString != null) && (anotherString.length() == length()) &&
1118 regionMatches(true, 0, anotherString, 0, length());
1122 * Compares two strings lexicographically.
1123 * The comparison is based on the Unicode value of each character in
1124 * the strings. The character sequence represented by this
1125 * <code>String</code> object is compared lexicographically to the
1126 * character sequence represented by the argument string. The result is
1127 * a negative integer if this <code>String</code> object
1128 * lexicographically precedes the argument string. The result is a
1129 * positive integer if this <code>String</code> object lexicographically
1130 * follows the argument string. The result is zero if the strings
1131 * are equal; <code>compareTo</code> returns <code>0</code> exactly when
1132 * the {@link #equals(Object)} method would return <code>true</code>.
1134 * This is the definition of lexicographic ordering. If two strings are
1135 * different, then either they have different characters at some index
1136 * that is a valid index for both strings, or their lengths are different,
1137 * or both. If they have different characters at one or more index
1138 * positions, let <i>k</i> be the smallest such index; then the string
1139 * whose character at position <i>k</i> has the smaller value, as
1140 * determined by using the < operator, lexicographically precedes the
1141 * other string. In this case, <code>compareTo</code> returns the
1142 * difference of the two character values at position <code>k</code> in
1143 * the two string -- that is, the value:
1145 * this.charAt(k)-anotherString.charAt(k)
1146 * </pre></blockquote>
1147 * If there is no index position at which they differ, then the shorter
1148 * string lexicographically precedes the longer string. In this case,
1149 * <code>compareTo</code> returns the difference of the lengths of the
1150 * strings -- that is, the value:
1152 * this.length()-anotherString.length()
1153 * </pre></blockquote>
1155 * @param anotherString the <code>String</code> to be compared.
1156 * @return the value <code>0</code> if the argument string is equal to
1157 * this string; a value less than <code>0</code> if this string
1158 * is lexicographically less than the string argument; and a
1159 * value greater than <code>0</code> if this string is
1160 * lexicographically greater than the string argument.
1162 public int compareTo(String anotherString) {
1163 int len1 = length();
1164 int len2 = anotherString.length();
1165 int n = Math.min(len1, len2);
1166 char v1[] = toCharArray();
1167 char v2[] = anotherString.toCharArray();
1169 int j = anotherString.offset();
1195 * A Comparator that orders <code>String</code> objects as by
1196 * <code>compareToIgnoreCase</code>. This comparator is serializable.
1198 * Note that this Comparator does <em>not</em> take locale into account,
1199 * and will result in an unsatisfactory ordering for certain locales.
1200 * The java.text package provides <em>Collators</em> to allow
1201 * locale-sensitive ordering.
1203 * @see java.text.Collator#compare(String, String)
1206 public static final Comparator<String> CASE_INSENSITIVE_ORDER
1207 = new CaseInsensitiveComparator();
1209 private static int offset() {
1213 private static class CaseInsensitiveComparator
1214 implements Comparator<String>, java.io.Serializable {
1215 // use serialVersionUID from JDK 1.2.2 for interoperability
1216 private static final long serialVersionUID = 8575799808933029326L;
1218 public int compare(String s1, String s2) {
1219 int n1 = s1.length();
1220 int n2 = s2.length();
1221 int min = Math.min(n1, n2);
1222 for (int i = 0; i < min; i++) {
1223 char c1 = s1.charAt(i);
1224 char c2 = s2.charAt(i);
1226 c1 = Character.toUpperCase(c1);
1227 c2 = Character.toUpperCase(c2);
1229 c1 = Character.toLowerCase(c1);
1230 c2 = Character.toLowerCase(c2);
1232 // No overflow because of numeric promotion
1243 * Compares two strings lexicographically, ignoring case
1244 * differences. This method returns an integer whose sign is that of
1245 * calling <code>compareTo</code> with normalized versions of the strings
1246 * where case differences have been eliminated by calling
1247 * <code>Character.toLowerCase(Character.toUpperCase(character))</code> on
1250 * Note that this method does <em>not</em> take locale into account,
1251 * and will result in an unsatisfactory ordering for certain locales.
1252 * The java.text package provides <em>collators</em> to allow
1253 * locale-sensitive ordering.
1255 * @param str the <code>String</code> to be compared.
1256 * @return a negative integer, zero, or a positive integer as the
1257 * specified String is greater than, equal to, or less
1258 * than this String, ignoring case considerations.
1259 * @see java.text.Collator#compare(String, String)
1262 public int compareToIgnoreCase(String str) {
1263 return CASE_INSENSITIVE_ORDER.compare(this, str);
1267 * Tests if two string regions are equal.
1269 * A substring of this <tt>String</tt> object is compared to a substring
1270 * of the argument other. The result is true if these substrings
1271 * represent identical character sequences. The substring of this
1272 * <tt>String</tt> object to be compared begins at index <tt>toffset</tt>
1273 * and has length <tt>len</tt>. The substring of other to be compared
1274 * begins at index <tt>ooffset</tt> and has length <tt>len</tt>. The
1275 * result is <tt>false</tt> if and only if at least one of the following
1277 * <ul><li><tt>toffset</tt> is negative.
1278 * <li><tt>ooffset</tt> is negative.
1279 * <li><tt>toffset+len</tt> is greater than the length of this
1280 * <tt>String</tt> object.
1281 * <li><tt>ooffset+len</tt> is greater than the length of the other
1283 * <li>There is some nonnegative integer <i>k</i> less than <tt>len</tt>
1285 * <tt>this.charAt(toffset+<i>k</i>) != other.charAt(ooffset+<i>k</i>)</tt>
1288 * @param toffset the starting offset of the subregion in this string.
1289 * @param other the string argument.
1290 * @param ooffset the starting offset of the subregion in the string
1292 * @param len the number of characters to compare.
1293 * @return <code>true</code> if the specified subregion of this string
1294 * exactly matches the specified subregion of the string argument;
1295 * <code>false</code> otherwise.
1297 public boolean regionMatches(int toffset, String other, int ooffset,
1299 char ta[] = toCharArray();
1300 int to = offset() + toffset;
1301 char pa[] = other.toCharArray();
1302 int po = other.offset() + ooffset;
1303 // Note: toffset, ooffset, or len might be near -1>>>1.
1304 if ((ooffset < 0) || (toffset < 0) || (toffset > (long)length() - len)
1305 || (ooffset > (long)other.length() - len)) {
1309 if (ta[to++] != pa[po++]) {
1317 * Tests if two string regions are equal.
1319 * A substring of this <tt>String</tt> object is compared to a substring
1320 * of the argument <tt>other</tt>. The result is <tt>true</tt> if these
1321 * substrings represent character sequences that are the same, ignoring
1322 * case if and only if <tt>ignoreCase</tt> is true. The substring of
1323 * this <tt>String</tt> object to be compared begins at index
1324 * <tt>toffset</tt> and has length <tt>len</tt>. The substring of
1325 * <tt>other</tt> to be compared begins at index <tt>ooffset</tt> and
1326 * has length <tt>len</tt>. The result is <tt>false</tt> if and only if
1327 * at least one of the following is true:
1328 * <ul><li><tt>toffset</tt> is negative.
1329 * <li><tt>ooffset</tt> is negative.
1330 * <li><tt>toffset+len</tt> is greater than the length of this
1331 * <tt>String</tt> object.
1332 * <li><tt>ooffset+len</tt> is greater than the length of the other
1334 * <li><tt>ignoreCase</tt> is <tt>false</tt> and there is some nonnegative
1335 * integer <i>k</i> less than <tt>len</tt> such that:
1337 * this.charAt(toffset+k) != other.charAt(ooffset+k)
1338 * </pre></blockquote>
1339 * <li><tt>ignoreCase</tt> is <tt>true</tt> and there is some nonnegative
1340 * integer <i>k</i> less than <tt>len</tt> such that:
1342 * Character.toLowerCase(this.charAt(toffset+k)) !=
1343 Character.toLowerCase(other.charAt(ooffset+k))
1344 * </pre></blockquote>
1347 * Character.toUpperCase(this.charAt(toffset+k)) !=
1348 * Character.toUpperCase(other.charAt(ooffset+k))
1349 * </pre></blockquote>
1352 * @param ignoreCase if <code>true</code>, ignore case when comparing
1354 * @param toffset the starting offset of the subregion in this
1356 * @param other the string argument.
1357 * @param ooffset the starting offset of the subregion in the string
1359 * @param len the number of characters to compare.
1360 * @return <code>true</code> if the specified subregion of this string
1361 * matches the specified subregion of the string argument;
1362 * <code>false</code> otherwise. Whether the matching is exact
1363 * or case insensitive depends on the <code>ignoreCase</code>
1366 public boolean regionMatches(boolean ignoreCase, int toffset,
1367 String other, int ooffset, int len) {
1368 char ta[] = toCharArray();
1369 int to = offset() + toffset;
1370 char pa[] = other.toCharArray();
1371 int po = other.offset() + ooffset;
1372 // Note: toffset, ooffset, or len might be near -1>>>1.
1373 if ((ooffset < 0) || (toffset < 0) || (toffset > (long)length() - len) ||
1374 (ooffset > (long)other.length() - len)) {
1384 // If characters don't match but case may be ignored,
1385 // try converting both characters to uppercase.
1386 // If the results match, then the comparison scan should
1388 char u1 = Character.toUpperCase(c1);
1389 char u2 = Character.toUpperCase(c2);
1393 // Unfortunately, conversion to uppercase does not work properly
1394 // for the Georgian alphabet, which has strange rules about case
1395 // conversion. So we need to make one last check before
1397 if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) {
1407 * Tests if the substring of this string beginning at the
1408 * specified index starts with the specified prefix.
1410 * @param prefix the prefix.
1411 * @param toffset where to begin looking in this string.
1412 * @return <code>true</code> if the character sequence represented by the
1413 * argument is a prefix of the substring of this object starting
1414 * at index <code>toffset</code>; <code>false</code> otherwise.
1415 * The result is <code>false</code> if <code>toffset</code> is
1416 * negative or greater than the length of this
1417 * <code>String</code> object; otherwise the result is the same
1418 * as the result of the expression
1420 * this.substring(toffset).startsWith(prefix)
1423 @JavaScriptBody(args = { "find", "from" }, body=
1424 "find = find.toString();\n" +
1425 "return this.toString().substring(from, from + find.length) === find;\n"
1427 public boolean startsWith(String prefix, int toffset) {
1428 char ta[] = toCharArray();
1429 int to = offset() + toffset;
1430 char pa[] = prefix.toCharArray();
1431 int po = prefix.offset();
1432 int pc = prefix.length();
1433 // Note: toffset might be near -1>>>1.
1434 if ((toffset < 0) || (toffset > length() - pc)) {
1438 if (ta[to++] != pa[po++]) {
1446 * Tests if this string starts with the specified prefix.
1448 * @param prefix the prefix.
1449 * @return <code>true</code> if the character sequence represented by the
1450 * argument is a prefix of the character sequence represented by
1451 * this string; <code>false</code> otherwise.
1452 * Note also that <code>true</code> will be returned if the
1453 * argument is an empty string or is equal to this
1454 * <code>String</code> object as determined by the
1455 * {@link #equals(Object)} method.
1458 public boolean startsWith(String prefix) {
1459 return startsWith(prefix, 0);
1463 * Tests if this string ends with the specified suffix.
1465 * @param suffix the suffix.
1466 * @return <code>true</code> if the character sequence represented by the
1467 * argument is a suffix of the character sequence represented by
1468 * this object; <code>false</code> otherwise. Note that the
1469 * result will be <code>true</code> if the argument is the
1470 * empty string or is equal to this <code>String</code> object
1471 * as determined by the {@link #equals(Object)} method.
1473 public boolean endsWith(String suffix) {
1474 return startsWith(suffix, length() - suffix.length());
1478 * Returns a hash code for this string. The hash code for a
1479 * <code>String</code> object is computed as
1481 * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
1482 * </pre></blockquote>
1483 * using <code>int</code> arithmetic, where <code>s[i]</code> is the
1484 * <i>i</i>th character of the string, <code>n</code> is the length of
1485 * the string, and <code>^</code> indicates exponentiation.
1486 * (The hash value of the empty string is zero.)
1488 * @return a hash code value for this object.
1490 public int hashCode() {
1491 return super.hashCode();
1493 int computeHashCode() {
1495 if (h == 0 && length() > 0) {
1499 for (int i = 0; i < len; i++) {
1500 h = 31*h + charAt(off++);
1507 * Returns the index within this string of the first occurrence of
1508 * the specified character. If a character with value
1509 * <code>ch</code> occurs in the character sequence represented by
1510 * this <code>String</code> object, then the index (in Unicode
1511 * code units) of the first such occurrence is returned. For
1512 * values of <code>ch</code> in the range from 0 to 0xFFFF
1513 * (inclusive), this is the smallest value <i>k</i> such that:
1515 * this.charAt(<i>k</i>) == ch
1516 * </pre></blockquote>
1517 * is true. For other values of <code>ch</code>, it is the
1518 * smallest value <i>k</i> such that:
1520 * this.codePointAt(<i>k</i>) == ch
1521 * </pre></blockquote>
1522 * is true. In either case, if no such character occurs in this
1523 * string, then <code>-1</code> is returned.
1525 * @param ch a character (Unicode code point).
1526 * @return the index of the first occurrence of the character in the
1527 * character sequence represented by this object, or
1528 * <code>-1</code> if the character does not occur.
1530 public int indexOf(int ch) {
1531 return indexOf(ch, 0);
1535 * Returns the index within this string of the first occurrence of the
1536 * specified character, starting the search at the specified index.
1538 * If a character with value <code>ch</code> occurs in the
1539 * character sequence represented by this <code>String</code>
1540 * object at an index no smaller than <code>fromIndex</code>, then
1541 * the index of the first such occurrence is returned. For values
1542 * of <code>ch</code> in the range from 0 to 0xFFFF (inclusive),
1543 * this is the smallest value <i>k</i> such that:
1545 * (this.charAt(<i>k</i>) == ch) && (<i>k</i> >= fromIndex)
1546 * </pre></blockquote>
1547 * is true. For other values of <code>ch</code>, it is the
1548 * smallest value <i>k</i> such that:
1550 * (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> >= fromIndex)
1551 * </pre></blockquote>
1552 * is true. In either case, if no such character occurs in this
1553 * string at or after position <code>fromIndex</code>, then
1554 * <code>-1</code> is returned.
1557 * There is no restriction on the value of <code>fromIndex</code>. If it
1558 * is negative, it has the same effect as if it were zero: this entire
1559 * string may be searched. If it is greater than the length of this
1560 * string, it has the same effect as if it were equal to the length of
1561 * this string: <code>-1</code> is returned.
1563 * <p>All indices are specified in <code>char</code> values
1564 * (Unicode code units).
1566 * @param ch a character (Unicode code point).
1567 * @param fromIndex the index to start the search from.
1568 * @return the index of the first occurrence of the character in the
1569 * character sequence represented by this object that is greater
1570 * than or equal to <code>fromIndex</code>, or <code>-1</code>
1571 * if the character does not occur.
1573 @JavaScriptBody(args = { "ch", "from" }, body =
1574 "if (typeof ch === 'number') ch = String.fromCharCode(ch);\n" +
1575 "return this.toString().indexOf(ch, from);\n"
1577 public int indexOf(int ch, int fromIndex) {
1578 if (fromIndex < 0) {
1580 } else if (fromIndex >= length()) {
1581 // Note: fromIndex might be near -1>>>1.
1585 if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
1586 // handle most cases here (ch is a BMP code point or a
1587 // negative value (invalid code point))
1588 final char[] value = this.toCharArray();
1589 final int offset = this.offset();
1590 final int max = offset + length();
1591 for (int i = offset + fromIndex; i < max ; i++) {
1592 if (value[i] == ch) {
1598 return indexOfSupplementary(ch, fromIndex);
1603 * Handles (rare) calls of indexOf with a supplementary character.
1605 private int indexOfSupplementary(int ch, int fromIndex) {
1606 if (Character.isValidCodePoint(ch)) {
1607 final char[] value = this.toCharArray();
1608 final int offset = this.offset();
1609 final char hi = Character.highSurrogate(ch);
1610 final char lo = Character.lowSurrogate(ch);
1611 final int max = offset + length() - 1;
1612 for (int i = offset + fromIndex; i < max; i++) {
1613 if (value[i] == hi && value[i+1] == lo) {
1622 * Returns the index within this string of the last occurrence of
1623 * the specified character. For values of <code>ch</code> in the
1624 * range from 0 to 0xFFFF (inclusive), the index (in Unicode code
1625 * units) returned is the largest value <i>k</i> such that:
1627 * this.charAt(<i>k</i>) == ch
1628 * </pre></blockquote>
1629 * is true. For other values of <code>ch</code>, it is the
1630 * largest value <i>k</i> such that:
1632 * this.codePointAt(<i>k</i>) == ch
1633 * </pre></blockquote>
1634 * is true. In either case, if no such character occurs in this
1635 * string, then <code>-1</code> is returned. The
1636 * <code>String</code> is searched backwards starting at the last
1639 * @param ch a character (Unicode code point).
1640 * @return the index of the last occurrence of the character in the
1641 * character sequence represented by this object, or
1642 * <code>-1</code> if the character does not occur.
1644 public int lastIndexOf(int ch) {
1645 return lastIndexOf(ch, length() - 1);
1649 * Returns the index within this string of the last occurrence of
1650 * the specified character, searching backward starting at the
1651 * specified index. For values of <code>ch</code> in the range
1652 * from 0 to 0xFFFF (inclusive), the index returned is the largest
1653 * value <i>k</i> such that:
1655 * (this.charAt(<i>k</i>) == ch) && (<i>k</i> <= fromIndex)
1656 * </pre></blockquote>
1657 * is true. For other values of <code>ch</code>, it is the
1658 * largest value <i>k</i> such that:
1660 * (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> <= fromIndex)
1661 * </pre></blockquote>
1662 * is true. In either case, if no such character occurs in this
1663 * string at or before position <code>fromIndex</code>, then
1664 * <code>-1</code> is returned.
1666 * <p>All indices are specified in <code>char</code> values
1667 * (Unicode code units).
1669 * @param ch a character (Unicode code point).
1670 * @param fromIndex the index to start the search from. There is no
1671 * restriction on the value of <code>fromIndex</code>. If it is
1672 * greater than or equal to the length of this string, it has
1673 * the same effect as if it were equal to one less than the
1674 * length of this string: this entire string may be searched.
1675 * If it is negative, it has the same effect as if it were -1:
1677 * @return the index of the last occurrence of the character in the
1678 * character sequence represented by this object that is less
1679 * than or equal to <code>fromIndex</code>, or <code>-1</code>
1680 * if the character does not occur before that point.
1682 @JavaScriptBody(args = { "ch", "from" }, body =
1683 "if (typeof ch === 'number') ch = String.fromCharCode(ch);\n" +
1684 "return this.toString().lastIndexOf(ch, from);"
1686 public int lastIndexOf(int ch, int fromIndex) {
1687 if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
1688 // handle most cases here (ch is a BMP code point or a
1689 // negative value (invalid code point))
1690 final char[] value = this.toCharArray();
1691 final int offset = this.offset();
1692 int i = offset + Math.min(fromIndex, length() - 1);
1693 for (; i >= offset ; i--) {
1694 if (value[i] == ch) {
1700 return lastIndexOfSupplementary(ch, fromIndex);
1705 * Handles (rare) calls of lastIndexOf with a supplementary character.
1707 private int lastIndexOfSupplementary(int ch, int fromIndex) {
1708 if (Character.isValidCodePoint(ch)) {
1709 final char[] value = this.toCharArray();
1710 final int offset = this.offset();
1711 char hi = Character.highSurrogate(ch);
1712 char lo = Character.lowSurrogate(ch);
1713 int i = offset + Math.min(fromIndex, length() - 2);
1714 for (; i >= offset; i--) {
1715 if (value[i] == hi && value[i+1] == lo) {
1724 * Returns the index within this string of the first occurrence of the
1725 * specified substring.
1727 * <p>The returned index is the smallest value <i>k</i> for which:
1729 * this.startsWith(str, <i>k</i>)
1730 * </pre></blockquote>
1731 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1733 * @param str the substring to search for.
1734 * @return the index of the first occurrence of the specified substring,
1735 * or {@code -1} if there is no such occurrence.
1737 public int indexOf(String str) {
1738 return indexOf(str, 0);
1742 * Returns the index within this string of the first occurrence of the
1743 * specified substring, starting at the specified index.
1745 * <p>The returned index is the smallest value <i>k</i> for which:
1747 * <i>k</i> >= fromIndex && this.startsWith(str, <i>k</i>)
1748 * </pre></blockquote>
1749 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1751 * @param str the substring to search for.
1752 * @param fromIndex the index from which to start the search.
1753 * @return the index of the first occurrence of the specified substring,
1754 * starting at the specified index,
1755 * or {@code -1} if there is no such occurrence.
1757 @JavaScriptBody(args = { "str", "fromIndex" }, body =
1758 "return this.toString().indexOf(str.toString(), fromIndex);"
1760 public native int indexOf(String str, int fromIndex);
1763 * Returns the index within this string of the last occurrence of the
1764 * specified substring. The last occurrence of the empty string ""
1765 * is considered to occur at the index value {@code this.length()}.
1767 * <p>The returned index is the largest value <i>k</i> for which:
1769 * this.startsWith(str, <i>k</i>)
1770 * </pre></blockquote>
1771 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1773 * @param str the substring to search for.
1774 * @return the index of the last occurrence of the specified substring,
1775 * or {@code -1} if there is no such occurrence.
1777 public int lastIndexOf(String str) {
1778 return lastIndexOf(str, length());
1782 * Returns the index within this string of the last occurrence of the
1783 * specified substring, searching backward starting at the specified index.
1785 * <p>The returned index is the largest value <i>k</i> for which:
1787 * <i>k</i> <= fromIndex && this.startsWith(str, <i>k</i>)
1788 * </pre></blockquote>
1789 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1791 * @param str the substring to search for.
1792 * @param fromIndex the index to start the search from.
1793 * @return the index of the last occurrence of the specified substring,
1794 * searching backward from the specified index,
1795 * or {@code -1} if there is no such occurrence.
1797 @JavaScriptBody(args = { "s", "from" }, body =
1798 "return this.toString().lastIndexOf(s.toString(), from);"
1800 public int lastIndexOf(String str, int fromIndex) {
1801 return lastIndexOf(toCharArray(), offset(), length(), str.toCharArray(), str.offset(), str.length(), fromIndex);
1805 * Code shared by String and StringBuffer to do searches. The
1806 * source is the character array being searched, and the target
1807 * is the string being searched for.
1809 * @param source the characters being searched.
1810 * @param sourceOffset offset of the source string.
1811 * @param sourceCount count of the source string.
1812 * @param target the characters being searched for.
1813 * @param targetOffset offset of the target string.
1814 * @param targetCount count of the target string.
1815 * @param fromIndex the index to begin searching from.
1817 static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
1818 char[] target, int targetOffset, int targetCount,
1821 * Check arguments; return immediately where possible. For
1822 * consistency, don't check for null str.
1824 int rightIndex = sourceCount - targetCount;
1825 if (fromIndex < 0) {
1828 if (fromIndex > rightIndex) {
1829 fromIndex = rightIndex;
1831 /* Empty string always matches. */
1832 if (targetCount == 0) {
1836 int strLastIndex = targetOffset + targetCount - 1;
1837 char strLastChar = target[strLastIndex];
1838 int min = sourceOffset + targetCount - 1;
1839 int i = min + fromIndex;
1841 startSearchForLastChar:
1843 while (i >= min && source[i] != strLastChar) {
1850 int start = j - (targetCount - 1);
1851 int k = strLastIndex - 1;
1854 if (source[j--] != target[k--]) {
1856 continue startSearchForLastChar;
1859 return start - sourceOffset + 1;
1864 * Returns a new string that is a substring of this string. The
1865 * substring begins with the character at the specified index and
1866 * extends to the end of this string. <p>
1869 * "unhappy".substring(2) returns "happy"
1870 * "Harbison".substring(3) returns "bison"
1871 * "emptiness".substring(9) returns "" (an empty string)
1872 * </pre></blockquote>
1874 * @param beginIndex the beginning index, inclusive.
1875 * @return the specified substring.
1876 * @exception IndexOutOfBoundsException if
1877 * <code>beginIndex</code> is negative or larger than the
1878 * length of this <code>String</code> object.
1880 public String substring(int beginIndex) {
1881 return substring(beginIndex, length());
1885 * Returns a new string that is a substring of this string. The
1886 * substring begins at the specified <code>beginIndex</code> and
1887 * extends to the character at index <code>endIndex - 1</code>.
1888 * Thus the length of the substring is <code>endIndex-beginIndex</code>.
1892 * "hamburger".substring(4, 8) returns "urge"
1893 * "smiles".substring(1, 5) returns "mile"
1894 * </pre></blockquote>
1896 * @param beginIndex the beginning index, inclusive.
1897 * @param endIndex the ending index, exclusive.
1898 * @return the specified substring.
1899 * @exception IndexOutOfBoundsException if the
1900 * <code>beginIndex</code> is negative, or
1901 * <code>endIndex</code> is larger than the length of
1902 * this <code>String</code> object, or
1903 * <code>beginIndex</code> is larger than
1904 * <code>endIndex</code>.
1906 @JavaScriptBody(args = { "beginIndex", "endIndex" }, body =
1907 "return this.toString().substring(beginIndex, endIndex);"
1909 public String substring(int beginIndex, int endIndex) {
1910 if (beginIndex < 0) {
1911 throw new StringIndexOutOfBoundsException(beginIndex);
1913 if (endIndex > length()) {
1914 throw new StringIndexOutOfBoundsException(endIndex);
1916 if (beginIndex > endIndex) {
1917 throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
1919 return ((beginIndex == 0) && (endIndex == length())) ? this :
1920 new String(toCharArray(), offset() + beginIndex, endIndex - beginIndex);
1924 * Returns a new character sequence that is a subsequence of this sequence.
1926 * <p> An invocation of this method of the form
1929 * str.subSequence(begin, end)</pre></blockquote>
1931 * behaves in exactly the same way as the invocation
1934 * str.substring(begin, end)</pre></blockquote>
1936 * This method is defined so that the <tt>String</tt> class can implement
1937 * the {@link CharSequence} interface. </p>
1939 * @param beginIndex the begin index, inclusive.
1940 * @param endIndex the end index, exclusive.
1941 * @return the specified subsequence.
1943 * @throws IndexOutOfBoundsException
1944 * if <tt>beginIndex</tt> or <tt>endIndex</tt> are negative,
1945 * if <tt>endIndex</tt> is greater than <tt>length()</tt>,
1946 * or if <tt>beginIndex</tt> is greater than <tt>startIndex</tt>
1951 public CharSequence subSequence(int beginIndex, int endIndex) {
1952 return this.substring(beginIndex, endIndex);
1956 * Concatenates the specified string to the end of this string.
1958 * If the length of the argument string is <code>0</code>, then this
1959 * <code>String</code> object is returned. Otherwise, a new
1960 * <code>String</code> object is created, representing a character
1961 * sequence that is the concatenation of the character sequence
1962 * represented by this <code>String</code> object and the character
1963 * sequence represented by the argument string.<p>
1966 * "cares".concat("s") returns "caress"
1967 * "to".concat("get").concat("her") returns "together"
1968 * </pre></blockquote>
1970 * @param str the <code>String</code> that is concatenated to the end
1971 * of this <code>String</code>.
1972 * @return a string that represents the concatenation of this object's
1973 * characters followed by the string argument's characters.
1975 public String concat(String str) {
1976 int otherLen = str.length();
1977 if (otherLen == 0) {
1980 char buf[] = new char[length() + otherLen];
1981 getChars(0, length(), buf, 0);
1982 str.getChars(0, otherLen, buf, length());
1983 return new String(buf, 0, length() + otherLen);
1987 * Returns a new string resulting from replacing all occurrences of
1988 * <code>oldChar</code> in this string with <code>newChar</code>.
1990 * If the character <code>oldChar</code> does not occur in the
1991 * character sequence represented by this <code>String</code> object,
1992 * then a reference to this <code>String</code> object is returned.
1993 * Otherwise, a new <code>String</code> object is created that
1994 * represents a character sequence identical to the character sequence
1995 * represented by this <code>String</code> object, except that every
1996 * occurrence of <code>oldChar</code> is replaced by an occurrence
1997 * of <code>newChar</code>.
2001 * "mesquite in your cellar".replace('e', 'o')
2002 * returns "mosquito in your collar"
2003 * "the war of baronets".replace('r', 'y')
2004 * returns "the way of bayonets"
2005 * "sparring with a purple porpoise".replace('p', 't')
2006 * returns "starring with a turtle tortoise"
2007 * "JonL".replace('q', 'x') returns "JonL" (no change)
2008 * </pre></blockquote>
2010 * @param oldChar the old character.
2011 * @param newChar the new character.
2012 * @return a string derived from this string by replacing every
2013 * occurrence of <code>oldChar</code> with <code>newChar</code>.
2015 @JavaScriptBody(args = { "arg1", "arg2" }, body =
2016 "if (typeof arg1 === 'number') arg1 = String.fromCharCode(arg1);\n" +
2017 "if (typeof arg2 === 'number') arg2 = String.fromCharCode(arg2);\n" +
2018 "var s = this.toString();\n" +
2020 " var ret = s.replace(arg1, arg2);\n" +
2021 " if (ret === s) {\n" +
2027 public String replace(char oldChar, char newChar) {
2028 if (oldChar != newChar) {
2031 char[] val = toCharArray(); /* avoid getfield opcode */
2032 int off = offset(); /* avoid getfield opcode */
2035 if (val[off + i] == oldChar) {
2040 char buf[] = new char[len];
2041 for (int j = 0 ; j < i ; j++) {
2042 buf[j] = val[off+j];
2045 char c = val[off + i];
2046 buf[i] = (c == oldChar) ? newChar : c;
2049 return new String(buf, 0, len);
2056 * Tells whether or not this string matches the given <a
2057 * href="../util/regex/Pattern.html#sum">regular expression</a>.
2059 * <p> An invocation of this method of the form
2060 * <i>str</i><tt>.matches(</tt><i>regex</i><tt>)</tt> yields exactly the
2061 * same result as the expression
2063 * <blockquote><tt> {@link java.util.regex.Pattern}.{@link
2064 * java.util.regex.Pattern#matches(String,CharSequence)
2065 * matches}(</tt><i>regex</i><tt>,</tt> <i>str</i><tt>)</tt></blockquote>
2068 * the regular expression to which this string is to be matched
2070 * @return <tt>true</tt> if, and only if, this string matches the
2071 * given regular expression
2073 * @throws PatternSyntaxException
2074 * if the regular expression's syntax is invalid
2076 * @see java.util.regex.Pattern
2081 @JavaScriptBody(args = { "regex" }, body =
2082 "var self = this.toString();\n"
2083 + "var re = new RegExp(regex.toString());\n"
2084 + "var r = re.exec(self);\n"
2085 + "return r != null && r.length > 0 && self.length == r[0].length;"
2087 public boolean matches(String regex) {
2088 throw new UnsupportedOperationException();
2092 * Returns true if and only if this string contains the specified
2093 * sequence of char values.
2095 * @param s the sequence to search for
2096 * @return true if this string contains <code>s</code>, false otherwise
2097 * @throws NullPointerException if <code>s</code> is <code>null</code>
2100 public boolean contains(CharSequence s) {
2101 return indexOf(s.toString()) > -1;
2105 * Replaces the first substring of this string that matches the given <a
2106 * href="../util/regex/Pattern.html#sum">regular expression</a> with the
2107 * given replacement.
2109 * <p> An invocation of this method of the form
2110 * <i>str</i><tt>.replaceFirst(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt>
2111 * yields exactly the same result as the expression
2114 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2115 * compile}(</tt><i>regex</i><tt>).{@link
2116 * java.util.regex.Pattern#matcher(java.lang.CharSequence)
2117 * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceFirst
2118 * replaceFirst}(</tt><i>repl</i><tt>)</tt></blockquote>
2121 * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the
2122 * replacement string may cause the results to be different than if it were
2123 * being treated as a literal replacement string; see
2124 * {@link java.util.regex.Matcher#replaceFirst}.
2125 * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
2126 * meaning of these characters, if desired.
2129 * the regular expression to which this string is to be matched
2130 * @param replacement
2131 * the string to be substituted for the first match
2133 * @return The resulting <tt>String</tt>
2135 * @throws PatternSyntaxException
2136 * if the regular expression's syntax is invalid
2138 * @see java.util.regex.Pattern
2143 public String replaceFirst(String regex, String replacement) {
2144 throw new UnsupportedOperationException();
2148 * Replaces each substring of this string that matches the given <a
2149 * href="../util/regex/Pattern.html#sum">regular expression</a> with the
2150 * given replacement.
2152 * <p> An invocation of this method of the form
2153 * <i>str</i><tt>.replaceAll(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt>
2154 * yields exactly the same result as the expression
2157 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2158 * compile}(</tt><i>regex</i><tt>).{@link
2159 * java.util.regex.Pattern#matcher(java.lang.CharSequence)
2160 * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceAll
2161 * replaceAll}(</tt><i>repl</i><tt>)</tt></blockquote>
2164 * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the
2165 * replacement string may cause the results to be different than if it were
2166 * being treated as a literal replacement string; see
2167 * {@link java.util.regex.Matcher#replaceAll Matcher.replaceAll}.
2168 * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
2169 * meaning of these characters, if desired.
2172 * the regular expression to which this string is to be matched
2173 * @param replacement
2174 * the string to be substituted for each match
2176 * @return The resulting <tt>String</tt>
2178 * @throws PatternSyntaxException
2179 * if the regular expression's syntax is invalid
2181 * @see java.util.regex.Pattern
2186 public String replaceAll(String regex, String replacement) {
2187 throw new UnsupportedOperationException();
2191 * Replaces each substring of this string that matches the literal target
2192 * sequence with the specified literal replacement sequence. The
2193 * replacement proceeds from the beginning of the string to the end, for
2194 * example, replacing "aa" with "b" in the string "aaa" will result in
2195 * "ba" rather than "ab".
2197 * @param target The sequence of char values to be replaced
2198 * @param replacement The replacement sequence of char values
2199 * @return The resulting string
2200 * @throws NullPointerException if <code>target</code> or
2201 * <code>replacement</code> is <code>null</code>.
2204 public String replace(CharSequence target, CharSequence replacement) {
2205 throw new UnsupportedOperationException("This one should be supported, but without dep on rest of regexp");
2209 * Splits this string around matches of the given
2210 * <a href="../util/regex/Pattern.html#sum">regular expression</a>.
2212 * <p> The array returned by this method contains each substring of this
2213 * string that is terminated by another substring that matches the given
2214 * expression or is terminated by the end of the string. The substrings in
2215 * the array are in the order in which they occur in this string. If the
2216 * expression does not match any part of the input then the resulting array
2217 * has just one element, namely this string.
2219 * <p> The <tt>limit</tt> parameter controls the number of times the
2220 * pattern is applied and therefore affects the length of the resulting
2221 * array. If the limit <i>n</i> is greater than zero then the pattern
2222 * will be applied at most <i>n</i> - 1 times, the array's
2223 * length will be no greater than <i>n</i>, and the array's last entry
2224 * will contain all input beyond the last matched delimiter. If <i>n</i>
2225 * is non-positive then the pattern will be applied as many times as
2226 * possible and the array can have any length. If <i>n</i> is zero then
2227 * the pattern will be applied as many times as possible, the array can
2228 * have any length, and trailing empty strings will be discarded.
2230 * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the
2231 * following results with these parameters:
2233 * <blockquote><table cellpadding=1 cellspacing=0 summary="Split example showing regex, limit, and result">
2239 * <tr><td align=center>:</td>
2240 * <td align=center>2</td>
2241 * <td><tt>{ "boo", "and:foo" }</tt></td></tr>
2242 * <tr><td align=center>:</td>
2243 * <td align=center>5</td>
2244 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2245 * <tr><td align=center>:</td>
2246 * <td align=center>-2</td>
2247 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2248 * <tr><td align=center>o</td>
2249 * <td align=center>5</td>
2250 * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
2251 * <tr><td align=center>o</td>
2252 * <td align=center>-2</td>
2253 * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
2254 * <tr><td align=center>o</td>
2255 * <td align=center>0</td>
2256 * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
2257 * </table></blockquote>
2259 * <p> An invocation of this method of the form
2260 * <i>str.</i><tt>split(</tt><i>regex</i><tt>,</tt> <i>n</i><tt>)</tt>
2261 * yields the same result as the expression
2264 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2265 * compile}<tt>(</tt><i>regex</i><tt>)</tt>.{@link
2266 * java.util.regex.Pattern#split(java.lang.CharSequence,int)
2267 * split}<tt>(</tt><i>str</i><tt>,</tt> <i>n</i><tt>)</tt>
2272 * the delimiting regular expression
2275 * the result threshold, as described above
2277 * @return the array of strings computed by splitting this string
2278 * around matches of the given regular expression
2280 * @throws PatternSyntaxException
2281 * if the regular expression's syntax is invalid
2283 * @see java.util.regex.Pattern
2288 public String[] split(String regex, int limit) {
2289 throw new UnsupportedOperationException("Needs regexp");
2293 * Splits this string around matches of the given <a
2294 * href="../util/regex/Pattern.html#sum">regular expression</a>.
2296 * <p> This method works as if by invoking the two-argument {@link
2297 * #split(String, int) split} method with the given expression and a limit
2298 * argument of zero. Trailing empty strings are therefore not included in
2299 * the resulting array.
2301 * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the following
2302 * results with these expressions:
2304 * <blockquote><table cellpadding=1 cellspacing=0 summary="Split examples showing regex and result">
2309 * <tr><td align=center>:</td>
2310 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2311 * <tr><td align=center>o</td>
2312 * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
2313 * </table></blockquote>
2317 * the delimiting regular expression
2319 * @return the array of strings computed by splitting this string
2320 * around matches of the given regular expression
2322 * @throws PatternSyntaxException
2323 * if the regular expression's syntax is invalid
2325 * @see java.util.regex.Pattern
2330 public String[] split(String regex) {
2331 return split(regex, 0);
2335 * Converts all of the characters in this <code>String</code> to lower
2336 * case using the rules of the given <code>Locale</code>. Case mapping is based
2337 * on the Unicode Standard version specified by the {@link java.lang.Character Character}
2338 * class. Since case mappings are not always 1:1 char mappings, the resulting
2339 * <code>String</code> may be a different length than the original <code>String</code>.
2341 * Examples of lowercase mappings are in the following table:
2342 * <table border="1" summary="Lowercase mapping examples showing language code of locale, upper case, lower case, and description">
2344 * <th>Language Code of Locale</th>
2345 * <th>Upper Case</th>
2346 * <th>Lower Case</th>
2347 * <th>Description</th>
2350 * <td>tr (Turkish)</td>
2351 * <td>\u0130</td>
2352 * <td>\u0069</td>
2353 * <td>capital letter I with dot above -> small letter i</td>
2356 * <td>tr (Turkish)</td>
2357 * <td>\u0049</td>
2358 * <td>\u0131</td>
2359 * <td>capital letter I -> small letter dotless i </td>
2363 * <td>French Fries</td>
2364 * <td>french fries</td>
2365 * <td>lowercased all chars in String</td>
2369 * <td><img src="doc-files/capiota.gif" alt="capiota"><img src="doc-files/capchi.gif" alt="capchi">
2370 * <img src="doc-files/captheta.gif" alt="captheta"><img src="doc-files/capupsil.gif" alt="capupsil">
2371 * <img src="doc-files/capsigma.gif" alt="capsigma"></td>
2372 * <td><img src="doc-files/iota.gif" alt="iota"><img src="doc-files/chi.gif" alt="chi">
2373 * <img src="doc-files/theta.gif" alt="theta"><img src="doc-files/upsilon.gif" alt="upsilon">
2374 * <img src="doc-files/sigma1.gif" alt="sigma"></td>
2375 * <td>lowercased all chars in String</td>
2379 * @param locale use the case transformation rules for this locale
2380 * @return the <code>String</code>, converted to lowercase.
2381 * @see java.lang.String#toLowerCase()
2382 * @see java.lang.String#toUpperCase()
2383 * @see java.lang.String#toUpperCase(Locale)
2386 // public String toLowerCase(Locale locale) {
2387 // if (locale == null) {
2388 // throw new NullPointerException();
2393 // /* Now check if there are any characters that need to be changed. */
2395 // for (firstUpper = 0 ; firstUpper < count; ) {
2396 // char c = value[offset+firstUpper];
2397 // if ((c >= Character.MIN_HIGH_SURROGATE) &&
2398 // (c <= Character.MAX_HIGH_SURROGATE)) {
2399 // int supplChar = codePointAt(firstUpper);
2400 // if (supplChar != Character.toLowerCase(supplChar)) {
2403 // firstUpper += Character.charCount(supplChar);
2405 // if (c != Character.toLowerCase(c)) {
2414 // char[] result = new char[count];
2415 // int resultOffset = 0; /* result may grow, so i+resultOffset
2416 // * is the write location in result */
2418 // /* Just copy the first few lowerCase characters. */
2419 // arraycopy(value, offset, result, 0, firstUpper);
2421 // String lang = locale.getLanguage();
2422 // boolean localeDependent =
2423 // (lang == "tr" || lang == "az" || lang == "lt");
2424 // char[] lowerCharArray;
2428 // for (int i = firstUpper; i < count; i += srcCount) {
2429 // srcChar = (int)value[offset+i];
2430 // if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
2431 // (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
2432 // srcChar = codePointAt(i);
2433 // srcCount = Character.charCount(srcChar);
2437 // if (localeDependent || srcChar == '\u03A3') { // GREEK CAPITAL LETTER SIGMA
2438 // lowerChar = ConditionalSpecialCasing.toLowerCaseEx(this, i, locale);
2439 // } else if (srcChar == '\u0130') { // LATIN CAPITAL LETTER I DOT
2440 // lowerChar = Character.ERROR;
2442 // lowerChar = Character.toLowerCase(srcChar);
2444 // if ((lowerChar == Character.ERROR) ||
2445 // (lowerChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
2446 // if (lowerChar == Character.ERROR) {
2447 // if (!localeDependent && srcChar == '\u0130') {
2449 // ConditionalSpecialCasing.toLowerCaseCharArray(this, i, Locale.ENGLISH);
2452 // ConditionalSpecialCasing.toLowerCaseCharArray(this, i, locale);
2454 // } else if (srcCount == 2) {
2455 // resultOffset += Character.toChars(lowerChar, result, i + resultOffset) - srcCount;
2458 // lowerCharArray = Character.toChars(lowerChar);
2461 // /* Grow result if needed */
2462 // int mapLen = lowerCharArray.length;
2463 // if (mapLen > srcCount) {
2464 // char[] result2 = new char[result.length + mapLen - srcCount];
2465 // arraycopy(result, 0, result2, 0,
2466 // i + resultOffset);
2467 // result = result2;
2469 // for (int x=0; x<mapLen; ++x) {
2470 // result[i+resultOffset+x] = lowerCharArray[x];
2472 // resultOffset += (mapLen - srcCount);
2474 // result[i+resultOffset] = (char)lowerChar;
2477 // return new String(0, count+resultOffset, result);
2481 * Converts all of the characters in this <code>String</code> to lower
2482 * case using the rules of the default locale. This is equivalent to calling
2483 * <code>toLowerCase(Locale.getDefault())</code>.
2485 * <b>Note:</b> This method is locale sensitive, and may produce unexpected
2486 * results if used for strings that are intended to be interpreted locale
2488 * Examples are programming language identifiers, protocol keys, and HTML
2490 * For instance, <code>"TITLE".toLowerCase()</code> in a Turkish locale
2491 * returns <code>"t\u005Cu0131tle"</code>, where '\u005Cu0131' is the
2492 * LATIN SMALL LETTER DOTLESS I character.
2493 * To obtain correct results for locale insensitive strings, use
2494 * <code>toLowerCase(Locale.ENGLISH)</code>.
2496 * @return the <code>String</code>, converted to lowercase.
2497 * @see java.lang.String#toLowerCase(Locale)
2499 @JavaScriptBody(args = {}, body = "return this.toLowerCase();")
2500 public String toLowerCase() {
2501 throw new UnsupportedOperationException("Should be supported but without connection to locale");
2505 * Converts all of the characters in this <code>String</code> to upper
2506 * case using the rules of the given <code>Locale</code>. Case mapping is based
2507 * on the Unicode Standard version specified by the {@link java.lang.Character Character}
2508 * class. Since case mappings are not always 1:1 char mappings, the resulting
2509 * <code>String</code> may be a different length than the original <code>String</code>.
2511 * Examples of locale-sensitive and 1:M case mappings are in the following table.
2513 * <table border="1" summary="Examples of locale-sensitive and 1:M case mappings. Shows Language code of locale, lower case, upper case, and description.">
2515 * <th>Language Code of Locale</th>
2516 * <th>Lower Case</th>
2517 * <th>Upper Case</th>
2518 * <th>Description</th>
2521 * <td>tr (Turkish)</td>
2522 * <td>\u0069</td>
2523 * <td>\u0130</td>
2524 * <td>small letter i -> capital letter I with dot above</td>
2527 * <td>tr (Turkish)</td>
2528 * <td>\u0131</td>
2529 * <td>\u0049</td>
2530 * <td>small letter dotless i -> capital letter I</td>
2534 * <td>\u00df</td>
2535 * <td>\u0053 \u0053</td>
2536 * <td>small letter sharp s -> two letters: SS</td>
2540 * <td>Fahrvergnügen</td>
2541 * <td>FAHRVERGNÜGEN</td>
2545 * @param locale use the case transformation rules for this locale
2546 * @return the <code>String</code>, converted to uppercase.
2547 * @see java.lang.String#toUpperCase()
2548 * @see java.lang.String#toLowerCase()
2549 * @see java.lang.String#toLowerCase(Locale)
2552 /* not for javascript
2553 public String toUpperCase(Locale locale) {
2554 if (locale == null) {
2555 throw new NullPointerException();
2560 // Now check if there are any characters that need to be changed.
2562 for (firstLower = 0 ; firstLower < count; ) {
2563 int c = (int)value[offset+firstLower];
2565 if ((c >= Character.MIN_HIGH_SURROGATE) &&
2566 (c <= Character.MAX_HIGH_SURROGATE)) {
2567 c = codePointAt(firstLower);
2568 srcCount = Character.charCount(c);
2572 int upperCaseChar = Character.toUpperCaseEx(c);
2573 if ((upperCaseChar == Character.ERROR) ||
2574 (c != upperCaseChar)) {
2577 firstLower += srcCount;
2582 char[] result = new char[count]; /* may grow *
2583 int resultOffset = 0; /* result may grow, so i+resultOffset
2584 * is the write location in result *
2586 /* Just copy the first few upperCase characters. *
2587 arraycopy(value, offset, result, 0, firstLower);
2589 String lang = locale.getLanguage();
2590 boolean localeDependent =
2591 (lang == "tr" || lang == "az" || lang == "lt");
2592 char[] upperCharArray;
2596 for (int i = firstLower; i < count; i += srcCount) {
2597 srcChar = (int)value[offset+i];
2598 if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
2599 (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
2600 srcChar = codePointAt(i);
2601 srcCount = Character.charCount(srcChar);
2605 if (localeDependent) {
2606 upperChar = ConditionalSpecialCasing.toUpperCaseEx(this, i, locale);
2608 upperChar = Character.toUpperCaseEx(srcChar);
2610 if ((upperChar == Character.ERROR) ||
2611 (upperChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
2612 if (upperChar == Character.ERROR) {
2613 if (localeDependent) {
2615 ConditionalSpecialCasing.toUpperCaseCharArray(this, i, locale);
2617 upperCharArray = Character.toUpperCaseCharArray(srcChar);
2619 } else if (srcCount == 2) {
2620 resultOffset += Character.toChars(upperChar, result, i + resultOffset) - srcCount;
2623 upperCharArray = Character.toChars(upperChar);
2626 /* Grow result if needed *
2627 int mapLen = upperCharArray.length;
2628 if (mapLen > srcCount) {
2629 char[] result2 = new char[result.length + mapLen - srcCount];
2630 arraycopy(result, 0, result2, 0,
2634 for (int x=0; x<mapLen; ++x) {
2635 result[i+resultOffset+x] = upperCharArray[x];
2637 resultOffset += (mapLen - srcCount);
2639 result[i+resultOffset] = (char)upperChar;
2642 return new String(0, count+resultOffset, result);
2647 * Converts all of the characters in this <code>String</code> to upper
2648 * case using the rules of the default locale. This method is equivalent to
2649 * <code>toUpperCase(Locale.getDefault())</code>.
2651 * <b>Note:</b> This method is locale sensitive, and may produce unexpected
2652 * results if used for strings that are intended to be interpreted locale
2654 * Examples are programming language identifiers, protocol keys, and HTML
2656 * For instance, <code>"title".toUpperCase()</code> in a Turkish locale
2657 * returns <code>"T\u005Cu0130TLE"</code>, where '\u005Cu0130' is the
2658 * LATIN CAPITAL LETTER I WITH DOT ABOVE character.
2659 * To obtain correct results for locale insensitive strings, use
2660 * <code>toUpperCase(Locale.ENGLISH)</code>.
2662 * @return the <code>String</code>, converted to uppercase.
2663 * @see java.lang.String#toUpperCase(Locale)
2665 @JavaScriptBody(args = {}, body = "return this.toUpperCase();")
2666 public String toUpperCase() {
2667 throw new UnsupportedOperationException();
2671 * Returns a copy of the string, with leading and trailing whitespace
2674 * If this <code>String</code> object represents an empty character
2675 * sequence, or the first and last characters of character sequence
2676 * represented by this <code>String</code> object both have codes
2677 * greater than <code>'\u0020'</code> (the space character), then a
2678 * reference to this <code>String</code> object is returned.
2680 * Otherwise, if there is no character with a code greater than
2681 * <code>'\u0020'</code> in the string, then a new
2682 * <code>String</code> object representing an empty string is created
2685 * Otherwise, let <i>k</i> be the index of the first character in the
2686 * string whose code is greater than <code>'\u0020'</code>, and let
2687 * <i>m</i> be the index of the last character in the string whose code
2688 * is greater than <code>'\u0020'</code>. A new <code>String</code>
2689 * object is created, representing the substring of this string that
2690 * begins with the character at index <i>k</i> and ends with the
2691 * character at index <i>m</i>-that is, the result of
2692 * <code>this.substring(<i>k</i>, <i>m</i>+1)</code>.
2694 * This method may be used to trim whitespace (as defined above) from
2695 * the beginning and end of a string.
2697 * @return A copy of this string with leading and trailing white
2698 * space removed, or this string if it has no leading or
2699 * trailing white space.
2701 public String trim() {
2704 int off = offset(); /* avoid getfield opcode */
2705 char[] val = toCharArray(); /* avoid getfield opcode */
2707 while ((st < len) && (val[off + st] <= ' ')) {
2710 while ((st < len) && (val[off + len - 1] <= ' ')) {
2713 return ((st > 0) || (len < length())) ? substring(st, len) : this;
2717 * This object (which is already a string!) is itself returned.
2719 * @return the string itself.
2721 @JavaScriptBody(args = {}, body = "return this.toString();")
2722 public String toString() {
2727 * Converts this string to a new character array.
2729 * @return a newly allocated character array whose length is the length
2730 * of this string and whose contents are initialized to contain
2731 * the character sequence represented by this string.
2733 public char[] toCharArray() {
2734 char result[] = new char[length()];
2735 getChars(0, length(), result, 0);
2740 * Returns a formatted string using the specified format string and
2743 * <p> The locale always used is the one returned by {@link
2744 * java.util.Locale#getDefault() Locale.getDefault()}.
2747 * A <a href="../util/Formatter.html#syntax">format string</a>
2750 * Arguments referenced by the format specifiers in the format
2751 * string. If there are more arguments than format specifiers, the
2752 * extra arguments are ignored. The number of arguments is
2753 * variable and may be zero. The maximum number of arguments is
2754 * limited by the maximum dimension of a Java array as defined by
2755 * <cite>The Java™ Virtual Machine Specification</cite>.
2756 * The behaviour on a
2757 * <tt>null</tt> argument depends on the <a
2758 * href="../util/Formatter.html#syntax">conversion</a>.
2760 * @throws IllegalFormatException
2761 * If a format string contains an illegal syntax, a format
2762 * specifier that is incompatible with the given arguments,
2763 * insufficient arguments given the format string, or other
2764 * illegal conditions. For specification of all possible
2765 * formatting errors, see the <a
2766 * href="../util/Formatter.html#detail">Details</a> section of the
2767 * formatter class specification.
2769 * @throws NullPointerException
2770 * If the <tt>format</tt> is <tt>null</tt>
2772 * @return A formatted string
2774 * @see java.util.Formatter
2777 public static String format(String format, Object ... args) {
2778 throw new UnsupportedOperationException();
2782 * Returns a formatted string using the specified locale, format string,
2786 * The {@linkplain java.util.Locale locale} to apply during
2787 * formatting. If <tt>l</tt> is <tt>null</tt> then no localization
2791 * A <a href="../util/Formatter.html#syntax">format string</a>
2794 * Arguments referenced by the format specifiers in the format
2795 * string. If there are more arguments than format specifiers, the
2796 * extra arguments are ignored. The number of arguments is
2797 * variable and may be zero. The maximum number of arguments is
2798 * limited by the maximum dimension of a Java array as defined by
2799 * <cite>The Java™ Virtual Machine Specification</cite>.
2800 * The behaviour on a
2801 * <tt>null</tt> argument depends on the <a
2802 * href="../util/Formatter.html#syntax">conversion</a>.
2804 * @throws IllegalFormatException
2805 * If a format string contains an illegal syntax, a format
2806 * specifier that is incompatible with the given arguments,
2807 * insufficient arguments given the format string, or other
2808 * illegal conditions. For specification of all possible
2809 * formatting errors, see the <a
2810 * href="../util/Formatter.html#detail">Details</a> section of the
2811 * formatter class specification
2813 * @throws NullPointerException
2814 * If the <tt>format</tt> is <tt>null</tt>
2816 * @return A formatted string
2818 * @see java.util.Formatter
2821 // public static String format(Locale l, String format, Object ... args) {
2822 // return new Formatter(l).format(format, args).toString();
2826 * Returns the string representation of the <code>Object</code> argument.
2828 * @param obj an <code>Object</code>.
2829 * @return if the argument is <code>null</code>, then a string equal to
2830 * <code>"null"</code>; otherwise, the value of
2831 * <code>obj.toString()</code> is returned.
2832 * @see java.lang.Object#toString()
2834 public static String valueOf(Object obj) {
2835 return (obj == null) ? "null" : obj.toString();
2839 * Returns the string representation of the <code>char</code> array
2840 * argument. The contents of the character array are copied; subsequent
2841 * modification of the character array does not affect the newly
2844 * @param data a <code>char</code> array.
2845 * @return a newly allocated string representing the same sequence of
2846 * characters contained in the character array argument.
2848 public static String valueOf(char data[]) {
2849 return new String(data);
2853 * Returns the string representation of a specific subarray of the
2854 * <code>char</code> array argument.
2856 * The <code>offset</code> argument is the index of the first
2857 * character of the subarray. The <code>count</code> argument
2858 * specifies the length of the subarray. The contents of the subarray
2859 * are copied; subsequent modification of the character array does not
2860 * affect the newly created string.
2862 * @param data the character array.
2863 * @param offset the initial offset into the value of the
2864 * <code>String</code>.
2865 * @param count the length of the value of the <code>String</code>.
2866 * @return a string representing the sequence of characters contained
2867 * in the subarray of the character array argument.
2868 * @exception IndexOutOfBoundsException if <code>offset</code> is
2869 * negative, or <code>count</code> is negative, or
2870 * <code>offset+count</code> is larger than
2871 * <code>data.length</code>.
2873 public static String valueOf(char data[], int offset, int count) {
2874 return new String(data, offset, count);
2878 * Returns a String that represents the character sequence in the
2881 * @param data the character array.
2882 * @param offset initial offset of the subarray.
2883 * @param count length of the subarray.
2884 * @return a <code>String</code> that contains the characters of the
2885 * specified subarray of the character array.
2887 public static String copyValueOf(char data[], int offset, int count) {
2888 // All public String constructors now copy the data.
2889 return new String(data, offset, count);
2893 * Returns a String that represents the character sequence in the
2896 * @param data the character array.
2897 * @return a <code>String</code> that contains the characters of the
2900 public static String copyValueOf(char data[]) {
2901 return copyValueOf(data, 0, data.length);
2905 * Returns the string representation of the <code>boolean</code> argument.
2907 * @param b a <code>boolean</code>.
2908 * @return if the argument is <code>true</code>, a string equal to
2909 * <code>"true"</code> is returned; otherwise, a string equal to
2910 * <code>"false"</code> is returned.
2912 public static String valueOf(boolean b) {
2913 return b ? "true" : "false";
2917 * Returns the string representation of the <code>char</code>
2920 * @param c a <code>char</code>.
2921 * @return a string of length <code>1</code> containing
2922 * as its single character the argument <code>c</code>.
2924 public static String valueOf(char c) {
2926 return new String(data, 0, 1);
2930 * Returns the string representation of the <code>int</code> argument.
2932 * The representation is exactly the one returned by the
2933 * <code>Integer.toString</code> method of one argument.
2935 * @param i an <code>int</code>.
2936 * @return a string representation of the <code>int</code> argument.
2937 * @see java.lang.Integer#toString(int, int)
2939 public static String valueOf(int i) {
2940 return Integer.toString(i);
2944 * Returns the string representation of the <code>long</code> argument.
2946 * The representation is exactly the one returned by the
2947 * <code>Long.toString</code> method of one argument.
2949 * @param l a <code>long</code>.
2950 * @return a string representation of the <code>long</code> argument.
2951 * @see java.lang.Long#toString(long)
2953 public static String valueOf(long l) {
2954 return Long.toString(l);
2958 * Returns the string representation of the <code>float</code> argument.
2960 * The representation is exactly the one returned by the
2961 * <code>Float.toString</code> method of one argument.
2963 * @param f a <code>float</code>.
2964 * @return a string representation of the <code>float</code> argument.
2965 * @see java.lang.Float#toString(float)
2967 public static String valueOf(float f) {
2968 return Float.toString(f);
2972 * Returns the string representation of the <code>double</code> argument.
2974 * The representation is exactly the one returned by the
2975 * <code>Double.toString</code> method of one argument.
2977 * @param d a <code>double</code>.
2978 * @return a string representation of the <code>double</code> argument.
2979 * @see java.lang.Double#toString(double)
2981 public static String valueOf(double d) {
2982 return Double.toString(d);
2986 * Returns a canonical representation for the string object.
2988 * A pool of strings, initially empty, is maintained privately by the
2989 * class <code>String</code>.
2991 * When the intern method is invoked, if the pool already contains a
2992 * string equal to this <code>String</code> object as determined by
2993 * the {@link #equals(Object)} method, then the string from the pool is
2994 * returned. Otherwise, this <code>String</code> object is added to the
2995 * pool and a reference to this <code>String</code> object is returned.
2997 * It follows that for any two strings <code>s</code> and <code>t</code>,
2998 * <code>s.intern() == t.intern()</code> is <code>true</code>
2999 * if and only if <code>s.equals(t)</code> is <code>true</code>.
3001 * All literal strings and string-valued constant expressions are
3002 * interned. String literals are defined in section 3.10.5 of the
3003 * <cite>The Java™ Language Specification</cite>.
3005 * @return a string that has the same contents as this string, but is
3006 * guaranteed to be from a pool of unique strings.
3008 public native String intern();