2 * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
28 import java.io.UnsupportedEncodingException;
29 import java.lang.reflect.InvocationTargetException;
30 import java.lang.reflect.Method;
31 import java.util.Comparator;
32 import java.util.Locale;
33 import org.apidesign.bck2brwsr.core.ExtraJavaScript;
34 import org.apidesign.bck2brwsr.core.JavaScriptBody;
35 import org.apidesign.bck2brwsr.core.JavaScriptOnly;
36 import org.apidesign.bck2brwsr.core.JavaScriptPrototype;
37 import org.apidesign.bck2brwsr.emul.lang.System;
40 * The <code>String</code> class represents character strings. All
41 * string literals in Java programs, such as <code>"abc"</code>, are
42 * implemented as instances of this class.
44 * Strings are constant; their values cannot be changed after they
45 * are created. String buffers support mutable strings.
46 * Because String objects are immutable they can be shared. For example:
47 * <p><blockquote><pre>
49 * </pre></blockquote><p>
51 * <p><blockquote><pre>
52 * char data[] = {'a', 'b', 'c'};
53 * String str = new String(data);
54 * </pre></blockquote><p>
55 * Here are some more examples of how strings can be used:
56 * <p><blockquote><pre>
57 * System.out.println("abc");
59 * System.out.println("abc" + cde);
60 * String c = "abc".substring(2,3);
61 * String d = cde.substring(1, 2);
64 * The class <code>String</code> includes methods for examining
65 * individual characters of the sequence, for comparing strings, for
66 * searching strings, for extracting substrings, and for creating a
67 * copy of a string with all characters translated to uppercase or to
68 * lowercase. Case mapping is based on the Unicode Standard version
69 * specified by the {@link java.lang.Character Character} class.
71 * The Java language provides special support for the string
72 * concatenation operator ( + ), and for conversion of
73 * other objects to strings. String concatenation is implemented
74 * through the <code>StringBuilder</code>(or <code>StringBuffer</code>)
75 * class and its <code>append</code> method.
76 * String conversions are implemented through the method
77 * <code>toString</code>, defined by <code>Object</code> and
78 * inherited by all classes in Java. For additional information on
79 * string concatenation and conversion, see Gosling, Joy, and Steele,
80 * <i>The Java Language Specification</i>.
82 * <p> Unless otherwise noted, passing a <tt>null</tt> argument to a constructor
83 * or method in this class will cause a {@link NullPointerException} to be
86 * <p>A <code>String</code> represents a string in the UTF-16 format
87 * in which <em>supplementary characters</em> are represented by <em>surrogate
88 * pairs</em> (see the section <a href="Character.html#unicode">Unicode
89 * Character Representations</a> in the <code>Character</code> class for
91 * Index values refer to <code>char</code> code units, so a supplementary
92 * character uses two positions in a <code>String</code>.
93 * <p>The <code>String</code> class provides methods for dealing with
94 * Unicode code points (i.e., characters), in addition to those for
95 * dealing with Unicode code units (i.e., <code>char</code> values).
98 * @author Arthur van Hoff
99 * @author Martin Buchholz
101 * @see java.lang.Object#toString()
102 * @see java.lang.StringBuffer
103 * @see java.lang.StringBuilder
104 * @see java.nio.charset.Charset
109 resource="/org/apidesign/vm4brwsr/emul/lang/java_lang_String.js",
112 @JavaScriptPrototype(container = "String.prototype", prototype = "new String")
113 public final class String
114 implements java.io.Serializable, Comparable<String>, CharSequence
116 /** real string to delegate to */
119 /** use serialVersionUID from JDK 1.0.2 for interoperability */
120 private static final long serialVersionUID = -6849794470754667710L;
125 @JavaScriptBody(args = {}, body =
126 "var p = vm.java_lang_String(false);\n"
127 + "p.toString = function() {\nreturn this._r().toString();\n};\n"
128 + "p.valueOf = function() {\nreturn this._r().valueOf();\n}\n"
130 private static native void registerToString();
133 * Class String is special cased within the Serialization Stream Protocol.
135 * A String instance is written initially into an ObjectOutputStream in the
138 * <code>TC_STRING</code> (utf String)
140 * The String is written by method <code>DataOutput.writeUTF</code>.
141 * A new handle is generated to refer to all future references to the
142 * string instance within the stream.
144 // private static final ObjectStreamField[] serialPersistentFields =
145 // new ObjectStreamField[0];
148 * Initializes a newly created {@code String} object so that it represents
149 * an empty character sequence. Note that use of this constructor is
150 * unnecessary since Strings are immutable.
157 * Initializes a newly created {@code String} object so that it represents
158 * the same sequence of characters as the argument; in other words, the
159 * newly created string is a copy of the argument string. Unless an
160 * explicit copy of {@code original} is needed, use of this constructor is
161 * unnecessary since Strings are immutable.
166 public String(String original) {
167 this.r = original.toString();
171 * Allocates a new {@code String} so that it represents the sequence of
172 * characters currently contained in the character array argument. The
173 * contents of the character array are copied; subsequent modification of
174 * the character array does not affect the newly created string.
177 * The initial value of the string
179 @JavaScriptBody(args = { "charArr" }, body=
180 "for (var i = 0; i < charArr.length; i++) {\n"
181 + " if (typeof charArr[i] === 'number') charArr[i] = String.fromCharCode(charArr[i]);\n"
183 + "this._r(charArr.join(''));\n"
185 public String(char value[]) {
189 * Allocates a new {@code String} that contains characters from a subarray
190 * of the character array argument. The {@code offset} argument is the
191 * index of the first character of the subarray and the {@code count}
192 * argument specifies the length of the subarray. The contents of the
193 * subarray are copied; subsequent modification of the character array does
194 * not affect the newly created string.
197 * Array that is the source of characters
205 * @throws IndexOutOfBoundsException
206 * If the {@code offset} and {@code count} arguments index
207 * characters outside the bounds of the {@code value} array
209 public String(char value[], int offset, int count) {
210 initFromCharArray(value, offset, count);
213 @JavaScriptBody(args = { "charArr", "off", "cnt" }, body =
214 "var up = off + cnt;\n" +
215 "for (var i = off; i < up; i++) {\n" +
216 " if (typeof charArr[i] === 'number') charArr[i] = String.fromCharCode(charArr[i]);\n" +
218 "this._r(charArr.slice(off, up).join(\"\"));\n"
220 private native void initFromCharArray(char value[], int offset, int count);
223 * Allocates a new {@code String} that contains characters from a subarray
224 * of the <a href="Character.html#unicode">Unicode code point</a> array
225 * argument. The {@code offset} argument is the index of the first code
226 * point of the subarray and the {@code count} argument specifies the
227 * length of the subarray. The contents of the subarray are converted to
228 * {@code char}s; subsequent modification of the {@code int} array does not
229 * affect the newly created string.
232 * Array that is the source of Unicode code points
240 * @throws IllegalArgumentException
241 * If any invalid Unicode code point is found in {@code
244 * @throws IndexOutOfBoundsException
245 * If the {@code offset} and {@code count} arguments index
246 * characters outside the bounds of the {@code codePoints} array
250 public String(int[] codePoints, int offset, int count) {
252 throw new StringIndexOutOfBoundsException(offset);
255 throw new StringIndexOutOfBoundsException(count);
257 // Note: offset or count might be near -1>>>1.
258 if (offset > codePoints.length - count) {
259 throw new StringIndexOutOfBoundsException(offset + count);
262 final int end = offset + count;
264 // Pass 1: Compute precise size of char[]
266 for (int i = offset; i < end; i++) {
267 int c = codePoints[i];
268 if (Character.isBmpCodePoint(c))
270 else if (Character.isValidCodePoint(c))
272 else throw new IllegalArgumentException(Integer.toString(c));
275 // Pass 2: Allocate and fill in char[]
276 final char[] v = new char[n];
278 for (int i = offset, j = 0; i < end; i++, j++) {
279 int c = codePoints[i];
280 if (Character.isBmpCodePoint(c))
283 Character.toSurrogates(c, v, j++);
286 this.r = new String(v, 0, n);
290 * Allocates a new {@code String} constructed from a subarray of an array
291 * of 8-bit integer values.
293 * <p> The {@code offset} argument is the index of the first byte of the
294 * subarray, and the {@code count} argument specifies the length of the
297 * <p> Each {@code byte} in the subarray is converted to a {@code char} as
298 * specified in the method above.
300 * @deprecated This method does not properly convert bytes into characters.
301 * As of JDK 1.1, the preferred way to do this is via the
302 * {@code String} constructors that take a {@link
303 * java.nio.charset.Charset}, charset name, or that use the platform's
307 * The bytes to be converted to characters
310 * The top 8 bits of each 16-bit Unicode code unit
317 * @throws IndexOutOfBoundsException
318 * If the {@code offset} or {@code count} argument is invalid
320 * @see #String(byte[], int)
321 * @see #String(byte[], int, int, java.lang.String)
322 * @see #String(byte[], int, int, java.nio.charset.Charset)
323 * @see #String(byte[], int, int)
324 * @see #String(byte[], java.lang.String)
325 * @see #String(byte[], java.nio.charset.Charset)
326 * @see #String(byte[])
329 public String(byte ascii[], int hibyte, int offset, int count) {
330 checkBounds(ascii, offset, count);
331 char value[] = new char[count];
334 for (int i = count ; i-- > 0 ;) {
335 value[i] = (char) (ascii[i + offset] & 0xff);
339 for (int i = count ; i-- > 0 ;) {
340 value[i] = (char) (hibyte | (ascii[i + offset] & 0xff));
343 initFromCharArray(value, offset, count);
347 * Allocates a new {@code String} containing characters constructed from
348 * an array of 8-bit integer values. Each character <i>c</i>in the
349 * resulting string is constructed from the corresponding component
350 * <i>b</i> in the byte array such that:
353 * <b><i>c</i></b> == (char)(((hibyte & 0xff) << 8)
354 * | (<b><i>b</i></b> & 0xff))
355 * </pre></blockquote>
357 * @deprecated This method does not properly convert bytes into
358 * characters. As of JDK 1.1, the preferred way to do this is via the
359 * {@code String} constructors that take a {@link
360 * java.nio.charset.Charset}, charset name, or that use the platform's
364 * The bytes to be converted to characters
367 * The top 8 bits of each 16-bit Unicode code unit
369 * @see #String(byte[], int, int, java.lang.String)
370 * @see #String(byte[], int, int, java.nio.charset.Charset)
371 * @see #String(byte[], int, int)
372 * @see #String(byte[], java.lang.String)
373 * @see #String(byte[], java.nio.charset.Charset)
374 * @see #String(byte[])
377 public String(byte ascii[], int hibyte) {
378 this(ascii, hibyte, 0, ascii.length);
381 /* Common private utility method used to bounds check the byte array
382 * and requested offset & length values used by the String(byte[],..)
385 private static void checkBounds(byte[] bytes, int offset, int length) {
387 throw new StringIndexOutOfBoundsException(length);
389 throw new StringIndexOutOfBoundsException(offset);
390 if (offset > bytes.length - length)
391 throw new StringIndexOutOfBoundsException(offset + length);
395 * Constructs a new {@code String} by decoding the specified subarray of
396 * bytes using the specified charset. The length of the new {@code String}
397 * is a function of the charset, and hence may not be equal to the length
400 * <p> The behavior of this constructor when the given bytes are not valid
401 * in the given charset is unspecified. The {@link
402 * java.nio.charset.CharsetDecoder} class should be used when more control
403 * over the decoding process is required.
406 * The bytes to be decoded into characters
409 * The index of the first byte to decode
412 * The number of bytes to decode
415 * The name of a supported {@linkplain java.nio.charset.Charset
418 * @throws UnsupportedEncodingException
419 * If the named charset is not supported
421 * @throws IndexOutOfBoundsException
422 * If the {@code offset} and {@code length} arguments index
423 * characters outside the bounds of the {@code bytes} array
427 public String(byte bytes[], int offset, int length, String charsetName)
428 throws UnsupportedEncodingException
430 this(checkUTF8(bytes, charsetName), offset, length);
434 * Constructs a new {@code String} by decoding the specified subarray of
435 * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
436 * The length of the new {@code String} is a function of the charset, and
437 * hence may not be equal to the length of the subarray.
439 * <p> This method always replaces malformed-input and unmappable-character
440 * sequences with this charset's default replacement string. The {@link
441 * java.nio.charset.CharsetDecoder} class should be used when more control
442 * over the decoding process is required.
445 * The bytes to be decoded into characters
448 * The index of the first byte to decode
451 * The number of bytes to decode
454 * The {@linkplain java.nio.charset.Charset charset} to be used to
455 * decode the {@code bytes}
457 * @throws IndexOutOfBoundsException
458 * If the {@code offset} and {@code length} arguments index
459 * characters outside the bounds of the {@code bytes} array
463 /* don't want dependnecy on Charset
464 public String(byte bytes[], int offset, int length, Charset charset) {
466 throw new NullPointerException("charset");
467 checkBounds(bytes, offset, length);
468 char[] v = StringCoding.decode(charset, bytes, offset, length);
470 this.count = v.length;
476 * Constructs a new {@code String} by decoding the specified array of bytes
477 * using the specified {@linkplain java.nio.charset.Charset charset}. The
478 * length of the new {@code String} is a function of the charset, and hence
479 * may not be equal to the length of the byte array.
481 * <p> The behavior of this constructor when the given bytes are not valid
482 * in the given charset is unspecified. The {@link
483 * java.nio.charset.CharsetDecoder} class should be used when more control
484 * over the decoding process is required.
487 * The bytes to be decoded into characters
490 * The name of a supported {@linkplain java.nio.charset.Charset
493 * @throws UnsupportedEncodingException
494 * If the named charset is not supported
498 public String(byte bytes[], String charsetName)
499 throws UnsupportedEncodingException
501 this(bytes, 0, bytes.length, charsetName);
505 * Constructs a new {@code String} by decoding the specified array of
506 * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
507 * The length of the new {@code String} is a function of the charset, and
508 * hence may not be equal to the length of the byte array.
510 * <p> This method always replaces malformed-input and unmappable-character
511 * sequences with this charset's default replacement string. The {@link
512 * java.nio.charset.CharsetDecoder} class should be used when more control
513 * over the decoding process is required.
516 * The bytes to be decoded into characters
519 * The {@linkplain java.nio.charset.Charset charset} to be used to
520 * decode the {@code bytes}
524 /* don't want dep on Charset
525 public String(byte bytes[], Charset charset) {
526 this(bytes, 0, bytes.length, charset);
531 * Constructs a new {@code String} by decoding the specified subarray of
532 * bytes using the platform's default charset. The length of the new
533 * {@code String} is a function of the charset, and hence may not be equal
534 * to the length of the subarray.
536 * <p> The behavior of this constructor when the given bytes are not valid
537 * in the default charset is unspecified. The {@link
538 * java.nio.charset.CharsetDecoder} class should be used when more control
539 * over the decoding process is required.
542 * The bytes to be decoded into characters
545 * The index of the first byte to decode
548 * The number of bytes to decode
550 * @throws IndexOutOfBoundsException
551 * If the {@code offset} and the {@code length} arguments index
552 * characters outside the bounds of the {@code bytes} array
556 public String(byte bytes[], int offset, int length) {
557 checkBounds(bytes, offset, length);
558 char[] v = new char[length];
559 int[] at = { offset };
560 int end = offset + length;
562 while (at[0] < end) {
563 int ch = nextChar(bytes, at);
564 v[chlen++] = (char)ch;
566 initFromCharArray(v, 0, chlen);
570 * Constructs a new {@code String} by decoding the specified array of bytes
571 * using the platform's default charset. The length of the new {@code
572 * String} is a function of the charset, and hence may not be equal to the
573 * length of the byte array.
575 * <p> The behavior of this constructor when the given bytes are not valid
576 * in the default charset is unspecified. The {@link
577 * java.nio.charset.CharsetDecoder} class should be used when more control
578 * over the decoding process is required.
581 * The bytes to be decoded into characters
585 public String(byte bytes[]) {
586 this(bytes, 0, bytes.length);
590 * Allocates a new string that contains the sequence of characters
591 * currently contained in the string buffer argument. The contents of the
592 * string buffer are copied; subsequent modification of the string buffer
593 * does not affect the newly created string.
596 * A {@code StringBuffer}
598 public String(StringBuffer buffer) {
599 this.r = buffer.toString();
603 * Allocates a new string that contains the sequence of characters
604 * currently contained in the string builder argument. The contents of the
605 * string builder are copied; subsequent modification of the string builder
606 * does not affect the newly created string.
608 * <p> This constructor is provided to ease migration to {@code
609 * StringBuilder}. Obtaining a string from a string builder via the {@code
610 * toString} method is likely to run faster and is generally preferred.
613 * A {@code StringBuilder}
617 public String(StringBuilder builder) {
618 this.r = builder.toString();
622 * Returns the length of this string.
623 * The length is equal to the number of <a href="Character.html#unicode">Unicode
624 * code units</a> in the string.
626 * @return the length of the sequence of characters represented by this
629 @JavaScriptBody(args = {}, body = "return this.toString().length;")
630 public int length() {
631 throw new UnsupportedOperationException();
635 * Returns <tt>true</tt> if, and only if, {@link #length()} is <tt>0</tt>.
637 * @return <tt>true</tt> if {@link #length()} is <tt>0</tt>, otherwise
642 @JavaScriptBody(args = {}, body="return this.toString().length === 0;")
643 public boolean isEmpty() {
644 return length() == 0;
648 * Returns the <code>char</code> value at the
649 * specified index. An index ranges from <code>0</code> to
650 * <code>length() - 1</code>. The first <code>char</code> value of the sequence
651 * is at index <code>0</code>, the next at index <code>1</code>,
652 * and so on, as for array indexing.
654 * <p>If the <code>char</code> value specified by the index is a
655 * <a href="Character.html#unicode">surrogate</a>, the surrogate
658 * @param index the index of the <code>char</code> value.
659 * @return the <code>char</code> value at the specified index of this string.
660 * The first <code>char</code> value is at index <code>0</code>.
661 * @exception IndexOutOfBoundsException if the <code>index</code>
662 * argument is negative or not less than the length of this
665 @JavaScriptBody(args = { "index" },
666 body = "return this.toString().charCodeAt(index);"
668 public char charAt(int index) {
669 throw new UnsupportedOperationException();
673 * Returns the character (Unicode code point) at the specified
674 * index. The index refers to <code>char</code> values
675 * (Unicode code units) and ranges from <code>0</code> to
676 * {@link #length()}<code> - 1</code>.
678 * <p> If the <code>char</code> value specified at the given index
679 * is in the high-surrogate range, the following index is less
680 * than the length of this <code>String</code>, and the
681 * <code>char</code> value at the following index is in the
682 * low-surrogate range, then the supplementary code point
683 * corresponding to this surrogate pair is returned. Otherwise,
684 * the <code>char</code> value at the given index is returned.
686 * @param index the index to the <code>char</code> values
687 * @return the code point value of the character at the
689 * @exception IndexOutOfBoundsException if the <code>index</code>
690 * argument is negative or not less than the length of this
694 public int codePointAt(int index) {
695 if ((index < 0) || (index >= length())) {
696 throw new StringIndexOutOfBoundsException(index);
698 return Character.codePointAtImpl(toCharArray(), offset() + index, offset() + length());
702 * Returns the character (Unicode code point) before the specified
703 * index. The index refers to <code>char</code> values
704 * (Unicode code units) and ranges from <code>1</code> to {@link
705 * CharSequence#length() length}.
707 * <p> If the <code>char</code> value at <code>(index - 1)</code>
708 * is in the low-surrogate range, <code>(index - 2)</code> is not
709 * negative, and the <code>char</code> value at <code>(index -
710 * 2)</code> is in the high-surrogate range, then the
711 * supplementary code point value of the surrogate pair is
712 * returned. If the <code>char</code> value at <code>index -
713 * 1</code> is an unpaired low-surrogate or a high-surrogate, the
714 * surrogate value is returned.
716 * @param index the index following the code point that should be returned
717 * @return the Unicode code point value before the given index.
718 * @exception IndexOutOfBoundsException if the <code>index</code>
719 * argument is less than 1 or greater than the length
723 public int codePointBefore(int index) {
725 if ((i < 0) || (i >= length())) {
726 throw new StringIndexOutOfBoundsException(index);
728 return Character.codePointBeforeImpl(toCharArray(), offset() + index, offset());
732 * Returns the number of Unicode code points in the specified text
733 * range of this <code>String</code>. The text range begins at the
734 * specified <code>beginIndex</code> and extends to the
735 * <code>char</code> at index <code>endIndex - 1</code>. Thus the
736 * length (in <code>char</code>s) of the text range is
737 * <code>endIndex-beginIndex</code>. Unpaired surrogates within
738 * the text range count as one code point each.
740 * @param beginIndex the index to the first <code>char</code> of
742 * @param endIndex the index after the last <code>char</code> of
744 * @return the number of Unicode code points in the specified text
746 * @exception IndexOutOfBoundsException if the
747 * <code>beginIndex</code> is negative, or <code>endIndex</code>
748 * is larger than the length of this <code>String</code>, or
749 * <code>beginIndex</code> is larger than <code>endIndex</code>.
752 public int codePointCount(int beginIndex, int endIndex) {
753 if (beginIndex < 0 || endIndex > length() || beginIndex > endIndex) {
754 throw new IndexOutOfBoundsException();
756 return Character.codePointCountImpl(toCharArray(), offset()+beginIndex, endIndex-beginIndex);
760 * Returns the index within this <code>String</code> that is
761 * offset from the given <code>index</code> by
762 * <code>codePointOffset</code> code points. Unpaired surrogates
763 * within the text range given by <code>index</code> and
764 * <code>codePointOffset</code> count as one code point each.
766 * @param index the index to be offset
767 * @param codePointOffset the offset in code points
768 * @return the index within this <code>String</code>
769 * @exception IndexOutOfBoundsException if <code>index</code>
770 * is negative or larger then the length of this
771 * <code>String</code>, or if <code>codePointOffset</code> is positive
772 * and the substring starting with <code>index</code> has fewer
773 * than <code>codePointOffset</code> code points,
774 * or if <code>codePointOffset</code> is negative and the substring
775 * before <code>index</code> has fewer than the absolute value
776 * of <code>codePointOffset</code> code points.
779 public int offsetByCodePoints(int index, int codePointOffset) {
780 if (index < 0 || index > length()) {
781 throw new IndexOutOfBoundsException();
783 return Character.offsetByCodePointsImpl(toCharArray(), offset(), length(),
784 offset()+index, codePointOffset) - offset();
788 * Copy characters from this string into dst starting at dstBegin.
789 * This method doesn't perform any range checking.
791 @JavaScriptBody(args = { "arr", "to" }, body =
792 "var s = this.toString();\n" +
793 "for (var i = 0; i < s.length; i++) {\n" +
794 " arr[to++] = s[i];\n" +
797 void getChars(char dst[], int dstBegin) {
798 System.arraycopy(toCharArray(), offset(), dst, dstBegin, length());
802 * Copies characters from this string into the destination character
805 * The first character to be copied is at index <code>srcBegin</code>;
806 * the last character to be copied is at index <code>srcEnd-1</code>
807 * (thus the total number of characters to be copied is
808 * <code>srcEnd-srcBegin</code>). The characters are copied into the
809 * subarray of <code>dst</code> starting at index <code>dstBegin</code>
810 * and ending at index:
811 * <p><blockquote><pre>
812 * dstbegin + (srcEnd-srcBegin) - 1
813 * </pre></blockquote>
815 * @param srcBegin index of the first character in the string
817 * @param srcEnd index after the last character in the string
819 * @param dst the destination array.
820 * @param dstBegin the start offset in the destination array.
821 * @exception IndexOutOfBoundsException If any of the following
823 * <ul><li><code>srcBegin</code> is negative.
824 * <li><code>srcBegin</code> is greater than <code>srcEnd</code>
825 * <li><code>srcEnd</code> is greater than the length of this
827 * <li><code>dstBegin</code> is negative
828 * <li><code>dstBegin+(srcEnd-srcBegin)</code> is larger than
829 * <code>dst.length</code></ul>
831 @JavaScriptBody(args = { "beg", "end", "arr", "dst" }, body=
832 "var s = this.toString();\n" +
833 "while (beg < end) {\n" +
834 " arr[dst++] = s.charCodeAt(beg++);\n" +
837 public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
839 throw new StringIndexOutOfBoundsException(srcBegin);
841 if (srcEnd > length()) {
842 throw new StringIndexOutOfBoundsException(srcEnd);
844 if (srcBegin > srcEnd) {
845 throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
847 System.arraycopy(toCharArray(), offset() + srcBegin, dst, dstBegin,
852 * Copies characters from this string into the destination byte array. Each
853 * byte receives the 8 low-order bits of the corresponding character. The
854 * eight high-order bits of each character are not copied and do not
855 * participate in the transfer in any way.
857 * <p> The first character to be copied is at index {@code srcBegin}; the
858 * last character to be copied is at index {@code srcEnd-1}. The total
859 * number of characters to be copied is {@code srcEnd-srcBegin}. The
860 * characters, converted to bytes, are copied into the subarray of {@code
861 * dst} starting at index {@code dstBegin} and ending at index:
864 * dstbegin + (srcEnd-srcBegin) - 1
865 * </pre></blockquote>
867 * @deprecated This method does not properly convert characters into
868 * bytes. As of JDK 1.1, the preferred way to do this is via the
869 * {@link #getBytes()} method, which uses the platform's default charset.
872 * Index of the first character in the string to copy
875 * Index after the last character in the string to copy
878 * The destination array
881 * The start offset in the destination array
883 * @throws IndexOutOfBoundsException
884 * If any of the following is true:
886 * <li> {@code srcBegin} is negative
887 * <li> {@code srcBegin} is greater than {@code srcEnd}
888 * <li> {@code srcEnd} is greater than the length of this String
889 * <li> {@code dstBegin} is negative
890 * <li> {@code dstBegin+(srcEnd-srcBegin)} is larger than {@code
895 public void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin) {
897 throw new StringIndexOutOfBoundsException(srcBegin);
899 if (srcEnd > length()) {
900 throw new StringIndexOutOfBoundsException(srcEnd);
902 if (srcBegin > srcEnd) {
903 throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
906 int n = offset() + srcEnd;
907 int i = offset() + srcBegin;
908 char[] val = toCharArray(); /* avoid getfield opcode */
911 dst[j++] = (byte)val[i++];
916 * Encodes this {@code String} into a sequence of bytes using the named
917 * charset, storing the result into a new byte array.
919 * <p> The behavior of this method when this string cannot be encoded in
920 * the given charset is unspecified. The {@link
921 * java.nio.charset.CharsetEncoder} class should be used when more control
922 * over the encoding process is required.
925 * The name of a supported {@linkplain java.nio.charset.Charset
928 * @return The resultant byte array
930 * @throws UnsupportedEncodingException
931 * If the named charset is not supported
935 public byte[] getBytes(String charsetName)
936 throws UnsupportedEncodingException
938 checkUTF8(null, charsetName);
943 * Encodes this {@code String} into a sequence of bytes using the given
944 * {@linkplain java.nio.charset.Charset charset}, storing the result into a
947 * <p> This method always replaces malformed-input and unmappable-character
948 * sequences with this charset's default replacement byte array. The
949 * {@link java.nio.charset.CharsetEncoder} class should be used when more
950 * control over the encoding process is required.
953 * The {@linkplain java.nio.charset.Charset} to be used to encode
956 * @return The resultant byte array
960 /* don't want dep on Charset
961 public byte[] getBytes(Charset charset) {
962 if (charset == null) throw new NullPointerException();
963 return StringCoding.encode(charset, value, offset, count);
968 * Encodes this {@code String} into a sequence of bytes using the
969 * platform's default charset, storing the result into a new byte array.
971 * <p> The behavior of this method when this string cannot be encoded in
972 * the default charset is unspecified. The {@link
973 * java.nio.charset.CharsetEncoder} class should be used when more control
974 * over the encoding process is required.
976 * @return The resultant byte array
980 public byte[] getBytes() {
982 byte[] arr = new byte[len];
983 for (int i = 0, j = 0; j < len; j++) {
984 final int v = charAt(j);
990 arr = System.expandArray(arr, arr.length + 1);
991 arr[i++] = (byte) (0xC0 | (v >> 6));
992 arr[i++] = (byte) (0x80 | (0x3F & v));
995 arr = System.expandArray(arr, arr.length + 2);
996 arr[i++] = (byte) (0xE0 | (v >> 12));
997 arr[i++] = (byte) (0x80 | ((v >> 6) & 0x7F));
998 arr[i++] = (byte) (0x80 | (0x3F & v));
1004 * Compares this string to the specified object. The result is {@code
1005 * true} if and only if the argument is not {@code null} and is a {@code
1006 * String} object that represents the same sequence of characters as this
1010 * The object to compare this {@code String} against
1012 * @return {@code true} if the given object represents a {@code String}
1013 * equivalent to this string, {@code false} otherwise
1015 * @see #compareTo(String)
1016 * @see #equalsIgnoreCase(String)
1018 @JavaScriptBody(args = { "obj" }, body =
1019 "return obj != null && obj.$instOf_java_lang_String && "
1020 + "this.toString() === obj.toString();"
1022 public boolean equals(Object anObject) {
1023 if (this == anObject) {
1026 if (anObject instanceof String) {
1027 String anotherString = (String)anObject;
1029 if (n == anotherString.length()) {
1030 char v1[] = toCharArray();
1031 char v2[] = anotherString.toCharArray();
1033 int j = anotherString.offset();
1035 if (v1[i++] != v2[j++])
1045 * Compares this string to the specified {@code StringBuffer}. The result
1046 * is {@code true} if and only if this {@code String} represents the same
1047 * sequence of characters as the specified {@code StringBuffer}.
1050 * The {@code StringBuffer} to compare this {@code String} against
1052 * @return {@code true} if this {@code String} represents the same
1053 * sequence of characters as the specified {@code StringBuffer},
1054 * {@code false} otherwise
1058 public boolean contentEquals(StringBuffer sb) {
1060 return contentEquals((CharSequence)sb);
1065 * Compares this string to the specified {@code CharSequence}. The result
1066 * is {@code true} if and only if this {@code String} represents the same
1067 * sequence of char values as the specified sequence.
1070 * The sequence to compare this {@code String} against
1072 * @return {@code true} if this {@code String} represents the same
1073 * sequence of char values as the specified sequence, {@code
1078 public boolean contentEquals(CharSequence cs) {
1079 if (length() != cs.length())
1081 // Argument is a StringBuffer, StringBuilder
1082 if (cs instanceof AbstractStringBuilder) {
1083 char v1[] = toCharArray();
1084 char v2[] = ((AbstractStringBuilder)cs).getValue();
1089 if (v1[i++] != v2[j++])
1094 // Argument is a String
1095 if (cs.equals(this))
1097 // Argument is a generic CharSequence
1098 char v1[] = toCharArray();
1103 if (v1[i++] != cs.charAt(j++))
1110 * Compares this {@code String} to another {@code String}, ignoring case
1111 * considerations. Two strings are considered equal ignoring case if they
1112 * are of the same length and corresponding characters in the two strings
1113 * are equal ignoring case.
1115 * <p> Two characters {@code c1} and {@code c2} are considered the same
1116 * ignoring case if at least one of the following is true:
1118 * <li> The two characters are the same (as compared by the
1119 * {@code ==} operator)
1120 * <li> Applying the method {@link
1121 * java.lang.Character#toUpperCase(char)} to each character
1122 * produces the same result
1123 * <li> Applying the method {@link
1124 * java.lang.Character#toLowerCase(char)} to each character
1125 * produces the same result
1128 * @param anotherString
1129 * The {@code String} to compare this {@code String} against
1131 * @return {@code true} if the argument is not {@code null} and it
1132 * represents an equivalent {@code String} ignoring case; {@code
1135 * @see #equals(Object)
1137 public boolean equalsIgnoreCase(String anotherString) {
1138 return (this == anotherString) ? true :
1139 (anotherString != null) && (anotherString.length() == length()) &&
1140 regionMatches(true, 0, anotherString, 0, length());
1144 * Compares two strings lexicographically.
1145 * The comparison is based on the Unicode value of each character in
1146 * the strings. The character sequence represented by this
1147 * <code>String</code> object is compared lexicographically to the
1148 * character sequence represented by the argument string. The result is
1149 * a negative integer if this <code>String</code> object
1150 * lexicographically precedes the argument string. The result is a
1151 * positive integer if this <code>String</code> object lexicographically
1152 * follows the argument string. The result is zero if the strings
1153 * are equal; <code>compareTo</code> returns <code>0</code> exactly when
1154 * the {@link #equals(Object)} method would return <code>true</code>.
1156 * This is the definition of lexicographic ordering. If two strings are
1157 * different, then either they have different characters at some index
1158 * that is a valid index for both strings, or their lengths are different,
1159 * or both. If they have different characters at one or more index
1160 * positions, let <i>k</i> be the smallest such index; then the string
1161 * whose character at position <i>k</i> has the smaller value, as
1162 * determined by using the < operator, lexicographically precedes the
1163 * other string. In this case, <code>compareTo</code> returns the
1164 * difference of the two character values at position <code>k</code> in
1165 * the two string -- that is, the value:
1167 * this.charAt(k)-anotherString.charAt(k)
1168 * </pre></blockquote>
1169 * If there is no index position at which they differ, then the shorter
1170 * string lexicographically precedes the longer string. In this case,
1171 * <code>compareTo</code> returns the difference of the lengths of the
1172 * strings -- that is, the value:
1174 * this.length()-anotherString.length()
1175 * </pre></blockquote>
1177 * @param anotherString the <code>String</code> to be compared.
1178 * @return the value <code>0</code> if the argument string is equal to
1179 * this string; a value less than <code>0</code> if this string
1180 * is lexicographically less than the string argument; and a
1181 * value greater than <code>0</code> if this string is
1182 * lexicographically greater than the string argument.
1184 public int compareTo(String anotherString) {
1185 int len1 = length();
1186 int len2 = anotherString.length();
1187 int n = Math.min(len1, len2);
1188 char v1[] = toCharArray();
1189 char v2[] = anotherString.toCharArray();
1191 int j = anotherString.offset();
1217 * A Comparator that orders <code>String</code> objects as by
1218 * <code>compareToIgnoreCase</code>. This comparator is serializable.
1220 * Note that this Comparator does <em>not</em> take locale into account,
1221 * and will result in an unsatisfactory ordering for certain locales.
1222 * The java.text package provides <em>Collators</em> to allow
1223 * locale-sensitive ordering.
1225 * @see java.text.Collator#compare(String, String)
1228 public static final Comparator<String> CASE_INSENSITIVE_ORDER
1229 = new CaseInsensitiveComparator();
1231 private static int offset() {
1235 private static class CaseInsensitiveComparator
1236 implements Comparator<String>, java.io.Serializable {
1237 // use serialVersionUID from JDK 1.2.2 for interoperability
1238 private static final long serialVersionUID = 8575799808933029326L;
1240 public int compare(String s1, String s2) {
1241 int n1 = s1.length();
1242 int n2 = s2.length();
1243 int min = Math.min(n1, n2);
1244 for (int i = 0; i < min; i++) {
1245 char c1 = s1.charAt(i);
1246 char c2 = s2.charAt(i);
1248 c1 = Character.toUpperCase(c1);
1249 c2 = Character.toUpperCase(c2);
1251 c1 = Character.toLowerCase(c1);
1252 c2 = Character.toLowerCase(c2);
1254 // No overflow because of numeric promotion
1265 * Compares two strings lexicographically, ignoring case
1266 * differences. This method returns an integer whose sign is that of
1267 * calling <code>compareTo</code> with normalized versions of the strings
1268 * where case differences have been eliminated by calling
1269 * <code>Character.toLowerCase(Character.toUpperCase(character))</code> on
1272 * Note that this method does <em>not</em> take locale into account,
1273 * and will result in an unsatisfactory ordering for certain locales.
1274 * The java.text package provides <em>collators</em> to allow
1275 * locale-sensitive ordering.
1277 * @param str the <code>String</code> to be compared.
1278 * @return a negative integer, zero, or a positive integer as the
1279 * specified String is greater than, equal to, or less
1280 * than this String, ignoring case considerations.
1281 * @see java.text.Collator#compare(String, String)
1284 public int compareToIgnoreCase(String str) {
1285 return CASE_INSENSITIVE_ORDER.compare(this, str);
1289 * Tests if two string regions are equal.
1291 * A substring of this <tt>String</tt> object is compared to a substring
1292 * of the argument other. The result is true if these substrings
1293 * represent identical character sequences. The substring of this
1294 * <tt>String</tt> object to be compared begins at index <tt>toffset</tt>
1295 * and has length <tt>len</tt>. The substring of other to be compared
1296 * begins at index <tt>ooffset</tt> and has length <tt>len</tt>. The
1297 * result is <tt>false</tt> if and only if at least one of the following
1299 * <ul><li><tt>toffset</tt> is negative.
1300 * <li><tt>ooffset</tt> is negative.
1301 * <li><tt>toffset+len</tt> is greater than the length of this
1302 * <tt>String</tt> object.
1303 * <li><tt>ooffset+len</tt> is greater than the length of the other
1305 * <li>There is some nonnegative integer <i>k</i> less than <tt>len</tt>
1307 * <tt>this.charAt(toffset+<i>k</i>) != other.charAt(ooffset+<i>k</i>)</tt>
1310 * @param toffset the starting offset of the subregion in this string.
1311 * @param other the string argument.
1312 * @param ooffset the starting offset of the subregion in the string
1314 * @param len the number of characters to compare.
1315 * @return <code>true</code> if the specified subregion of this string
1316 * exactly matches the specified subregion of the string argument;
1317 * <code>false</code> otherwise.
1319 public boolean regionMatches(int toffset, String other, int ooffset,
1321 char ta[] = toCharArray();
1322 int to = offset() + toffset;
1323 char pa[] = other.toCharArray();
1324 int po = other.offset() + ooffset;
1325 // Note: toffset, ooffset, or len might be near -1>>>1.
1326 if ((ooffset < 0) || (toffset < 0) || (toffset > (long)length() - len)
1327 || (ooffset > (long)other.length() - len)) {
1331 if (ta[to++] != pa[po++]) {
1339 * Tests if two string regions are equal.
1341 * A substring of this <tt>String</tt> object is compared to a substring
1342 * of the argument <tt>other</tt>. The result is <tt>true</tt> if these
1343 * substrings represent character sequences that are the same, ignoring
1344 * case if and only if <tt>ignoreCase</tt> is true. The substring of
1345 * this <tt>String</tt> object to be compared begins at index
1346 * <tt>toffset</tt> and has length <tt>len</tt>. The substring of
1347 * <tt>other</tt> to be compared begins at index <tt>ooffset</tt> and
1348 * has length <tt>len</tt>. The result is <tt>false</tt> if and only if
1349 * at least one of the following is true:
1350 * <ul><li><tt>toffset</tt> is negative.
1351 * <li><tt>ooffset</tt> is negative.
1352 * <li><tt>toffset+len</tt> is greater than the length of this
1353 * <tt>String</tt> object.
1354 * <li><tt>ooffset+len</tt> is greater than the length of the other
1356 * <li><tt>ignoreCase</tt> is <tt>false</tt> and there is some nonnegative
1357 * integer <i>k</i> less than <tt>len</tt> such that:
1359 * this.charAt(toffset+k) != other.charAt(ooffset+k)
1360 * </pre></blockquote>
1361 * <li><tt>ignoreCase</tt> is <tt>true</tt> and there is some nonnegative
1362 * integer <i>k</i> less than <tt>len</tt> such that:
1364 * Character.toLowerCase(this.charAt(toffset+k)) !=
1365 Character.toLowerCase(other.charAt(ooffset+k))
1366 * </pre></blockquote>
1369 * Character.toUpperCase(this.charAt(toffset+k)) !=
1370 * Character.toUpperCase(other.charAt(ooffset+k))
1371 * </pre></blockquote>
1374 * @param ignoreCase if <code>true</code>, ignore case when comparing
1376 * @param toffset the starting offset of the subregion in this
1378 * @param other the string argument.
1379 * @param ooffset the starting offset of the subregion in the string
1381 * @param len the number of characters to compare.
1382 * @return <code>true</code> if the specified subregion of this string
1383 * matches the specified subregion of the string argument;
1384 * <code>false</code> otherwise. Whether the matching is exact
1385 * or case insensitive depends on the <code>ignoreCase</code>
1388 public boolean regionMatches(boolean ignoreCase, int toffset,
1389 String other, int ooffset, int len) {
1390 char ta[] = toCharArray();
1391 int to = offset() + toffset;
1392 char pa[] = other.toCharArray();
1393 int po = other.offset() + ooffset;
1394 // Note: toffset, ooffset, or len might be near -1>>>1.
1395 if ((ooffset < 0) || (toffset < 0) || (toffset > (long)length() - len) ||
1396 (ooffset > (long)other.length() - len)) {
1406 // If characters don't match but case may be ignored,
1407 // try converting both characters to uppercase.
1408 // If the results match, then the comparison scan should
1410 char u1 = Character.toUpperCase(c1);
1411 char u2 = Character.toUpperCase(c2);
1415 // Unfortunately, conversion to uppercase does not work properly
1416 // for the Georgian alphabet, which has strange rules about case
1417 // conversion. So we need to make one last check before
1419 if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) {
1429 * Tests if the substring of this string beginning at the
1430 * specified index starts with the specified prefix.
1432 * @param prefix the prefix.
1433 * @param toffset where to begin looking in this string.
1434 * @return <code>true</code> if the character sequence represented by the
1435 * argument is a prefix of the substring of this object starting
1436 * at index <code>toffset</code>; <code>false</code> otherwise.
1437 * The result is <code>false</code> if <code>toffset</code> is
1438 * negative or greater than the length of this
1439 * <code>String</code> object; otherwise the result is the same
1440 * as the result of the expression
1442 * this.substring(toffset).startsWith(prefix)
1445 @JavaScriptBody(args = { "find", "from" }, body=
1446 "find = find.toString();\n" +
1447 "return this.toString().substring(from, from + find.length) === find;\n"
1449 public boolean startsWith(String prefix, int toffset) {
1450 char ta[] = toCharArray();
1451 int to = offset() + toffset;
1452 char pa[] = prefix.toCharArray();
1453 int po = prefix.offset();
1454 int pc = prefix.length();
1455 // Note: toffset might be near -1>>>1.
1456 if ((toffset < 0) || (toffset > length() - pc)) {
1460 if (ta[to++] != pa[po++]) {
1468 * Tests if this string starts with the specified prefix.
1470 * @param prefix the prefix.
1471 * @return <code>true</code> if the character sequence represented by the
1472 * argument is a prefix of the character sequence represented by
1473 * this string; <code>false</code> otherwise.
1474 * Note also that <code>true</code> will be returned if the
1475 * argument is an empty string or is equal to this
1476 * <code>String</code> object as determined by the
1477 * {@link #equals(Object)} method.
1480 public boolean startsWith(String prefix) {
1481 return startsWith(prefix, 0);
1485 * Tests if this string ends with the specified suffix.
1487 * @param suffix the suffix.
1488 * @return <code>true</code> if the character sequence represented by the
1489 * argument is a suffix of the character sequence represented by
1490 * this object; <code>false</code> otherwise. Note that the
1491 * result will be <code>true</code> if the argument is the
1492 * empty string or is equal to this <code>String</code> object
1493 * as determined by the {@link #equals(Object)} method.
1495 public boolean endsWith(String suffix) {
1496 return startsWith(suffix, length() - suffix.length());
1500 * Returns a hash code for this string. The hash code for a
1501 * <code>String</code> object is computed as
1503 * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
1504 * </pre></blockquote>
1505 * using <code>int</code> arithmetic, where <code>s[i]</code> is the
1506 * <i>i</i>th character of the string, <code>n</code> is the length of
1507 * the string, and <code>^</code> indicates exponentiation.
1508 * (The hash value of the empty string is zero.)
1510 * @return a hash code value for this object.
1512 public int hashCode() {
1513 return super.hashCode();
1515 int computeHashCode() {
1517 if (h == 0 && length() > 0) {
1521 for (int i = 0; i < len; i++) {
1522 h = 31*h + charAt(off++);
1529 * Returns the index within this string of the first occurrence of
1530 * the specified character. If a character with value
1531 * <code>ch</code> occurs in the character sequence represented by
1532 * this <code>String</code> object, then the index (in Unicode
1533 * code units) of the first such occurrence is returned. For
1534 * values of <code>ch</code> in the range from 0 to 0xFFFF
1535 * (inclusive), this is the smallest value <i>k</i> such that:
1537 * this.charAt(<i>k</i>) == ch
1538 * </pre></blockquote>
1539 * is true. For other values of <code>ch</code>, it is the
1540 * smallest value <i>k</i> such that:
1542 * this.codePointAt(<i>k</i>) == ch
1543 * </pre></blockquote>
1544 * is true. In either case, if no such character occurs in this
1545 * string, then <code>-1</code> is returned.
1547 * @param ch a character (Unicode code point).
1548 * @return the index of the first occurrence of the character in the
1549 * character sequence represented by this object, or
1550 * <code>-1</code> if the character does not occur.
1552 public int indexOf(int ch) {
1553 return indexOf(ch, 0);
1557 * Returns the index within this string of the first occurrence of the
1558 * specified character, starting the search at the specified index.
1560 * If a character with value <code>ch</code> occurs in the
1561 * character sequence represented by this <code>String</code>
1562 * object at an index no smaller than <code>fromIndex</code>, then
1563 * the index of the first such occurrence is returned. For values
1564 * of <code>ch</code> in the range from 0 to 0xFFFF (inclusive),
1565 * this is the smallest value <i>k</i> such that:
1567 * (this.charAt(<i>k</i>) == ch) && (<i>k</i> >= fromIndex)
1568 * </pre></blockquote>
1569 * is true. For other values of <code>ch</code>, it is the
1570 * smallest value <i>k</i> such that:
1572 * (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> >= fromIndex)
1573 * </pre></blockquote>
1574 * is true. In either case, if no such character occurs in this
1575 * string at or after position <code>fromIndex</code>, then
1576 * <code>-1</code> is returned.
1579 * There is no restriction on the value of <code>fromIndex</code>. If it
1580 * is negative, it has the same effect as if it were zero: this entire
1581 * string may be searched. If it is greater than the length of this
1582 * string, it has the same effect as if it were equal to the length of
1583 * this string: <code>-1</code> is returned.
1585 * <p>All indices are specified in <code>char</code> values
1586 * (Unicode code units).
1588 * @param ch a character (Unicode code point).
1589 * @param fromIndex the index to start the search from.
1590 * @return the index of the first occurrence of the character in the
1591 * character sequence represented by this object that is greater
1592 * than or equal to <code>fromIndex</code>, or <code>-1</code>
1593 * if the character does not occur.
1595 @JavaScriptBody(args = { "ch", "from" }, body =
1596 "if (typeof ch === 'number') ch = String.fromCharCode(ch);\n" +
1597 "return this.toString().indexOf(ch, from);\n"
1599 public int indexOf(int ch, int fromIndex) {
1600 if (fromIndex < 0) {
1602 } else if (fromIndex >= length()) {
1603 // Note: fromIndex might be near -1>>>1.
1607 if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
1608 // handle most cases here (ch is a BMP code point or a
1609 // negative value (invalid code point))
1610 final char[] value = this.toCharArray();
1611 final int offset = this.offset();
1612 final int max = offset + length();
1613 for (int i = offset + fromIndex; i < max ; i++) {
1614 if (value[i] == ch) {
1620 return indexOfSupplementary(ch, fromIndex);
1625 * Handles (rare) calls of indexOf with a supplementary character.
1627 private int indexOfSupplementary(int ch, int fromIndex) {
1628 if (Character.isValidCodePoint(ch)) {
1629 final char[] value = this.toCharArray();
1630 final int offset = this.offset();
1631 final char hi = Character.highSurrogate(ch);
1632 final char lo = Character.lowSurrogate(ch);
1633 final int max = offset + length() - 1;
1634 for (int i = offset + fromIndex; i < max; i++) {
1635 if (value[i] == hi && value[i+1] == lo) {
1644 * Returns the index within this string of the last occurrence of
1645 * the specified character. For values of <code>ch</code> in the
1646 * range from 0 to 0xFFFF (inclusive), the index (in Unicode code
1647 * units) returned is the largest value <i>k</i> such that:
1649 * this.charAt(<i>k</i>) == ch
1650 * </pre></blockquote>
1651 * is true. For other values of <code>ch</code>, it is the
1652 * largest value <i>k</i> such that:
1654 * this.codePointAt(<i>k</i>) == ch
1655 * </pre></blockquote>
1656 * is true. In either case, if no such character occurs in this
1657 * string, then <code>-1</code> is returned. The
1658 * <code>String</code> is searched backwards starting at the last
1661 * @param ch a character (Unicode code point).
1662 * @return the index of the last occurrence of the character in the
1663 * character sequence represented by this object, or
1664 * <code>-1</code> if the character does not occur.
1666 public int lastIndexOf(int ch) {
1667 return lastIndexOf(ch, length() - 1);
1671 * Returns the index within this string of the last occurrence of
1672 * the specified character, searching backward starting at the
1673 * specified index. For values of <code>ch</code> in the range
1674 * from 0 to 0xFFFF (inclusive), the index returned is the largest
1675 * value <i>k</i> such that:
1677 * (this.charAt(<i>k</i>) == ch) && (<i>k</i> <= fromIndex)
1678 * </pre></blockquote>
1679 * is true. For other values of <code>ch</code>, it is the
1680 * largest value <i>k</i> such that:
1682 * (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> <= fromIndex)
1683 * </pre></blockquote>
1684 * is true. In either case, if no such character occurs in this
1685 * string at or before position <code>fromIndex</code>, then
1686 * <code>-1</code> is returned.
1688 * <p>All indices are specified in <code>char</code> values
1689 * (Unicode code units).
1691 * @param ch a character (Unicode code point).
1692 * @param fromIndex the index to start the search from. There is no
1693 * restriction on the value of <code>fromIndex</code>. If it is
1694 * greater than or equal to the length of this string, it has
1695 * the same effect as if it were equal to one less than the
1696 * length of this string: this entire string may be searched.
1697 * If it is negative, it has the same effect as if it were -1:
1699 * @return the index of the last occurrence of the character in the
1700 * character sequence represented by this object that is less
1701 * than or equal to <code>fromIndex</code>, or <code>-1</code>
1702 * if the character does not occur before that point.
1704 @JavaScriptBody(args = { "ch", "from" }, body =
1705 "if (typeof ch === 'number') ch = String.fromCharCode(ch);\n" +
1706 "return this.toString().lastIndexOf(ch, from);"
1708 public int lastIndexOf(int ch, int fromIndex) {
1709 if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
1710 // handle most cases here (ch is a BMP code point or a
1711 // negative value (invalid code point))
1712 final char[] value = this.toCharArray();
1713 final int offset = this.offset();
1714 int i = offset + Math.min(fromIndex, length() - 1);
1715 for (; i >= offset ; i--) {
1716 if (value[i] == ch) {
1722 return lastIndexOfSupplementary(ch, fromIndex);
1727 * Handles (rare) calls of lastIndexOf with a supplementary character.
1729 private int lastIndexOfSupplementary(int ch, int fromIndex) {
1730 if (Character.isValidCodePoint(ch)) {
1731 final char[] value = this.toCharArray();
1732 final int offset = this.offset();
1733 char hi = Character.highSurrogate(ch);
1734 char lo = Character.lowSurrogate(ch);
1735 int i = offset + Math.min(fromIndex, length() - 2);
1736 for (; i >= offset; i--) {
1737 if (value[i] == hi && value[i+1] == lo) {
1746 * Returns the index within this string of the first occurrence of the
1747 * specified substring.
1749 * <p>The returned index is the smallest value <i>k</i> for which:
1751 * this.startsWith(str, <i>k</i>)
1752 * </pre></blockquote>
1753 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1755 * @param str the substring to search for.
1756 * @return the index of the first occurrence of the specified substring,
1757 * or {@code -1} if there is no such occurrence.
1759 public int indexOf(String str) {
1760 return indexOf(str, 0);
1764 * Returns the index within this string of the first occurrence of the
1765 * specified substring, starting at the specified index.
1767 * <p>The returned index is the smallest value <i>k</i> for which:
1769 * <i>k</i> >= fromIndex && 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 * @param fromIndex the index from which to start the search.
1775 * @return the index of the first occurrence of the specified substring,
1776 * starting at the specified index,
1777 * or {@code -1} if there is no such occurrence.
1779 @JavaScriptBody(args = { "str", "fromIndex" }, body =
1780 "return this.toString().indexOf(str.toString(), fromIndex);"
1782 public native int indexOf(String str, int fromIndex);
1785 * Returns the index within this string of the last occurrence of the
1786 * specified substring. The last occurrence of the empty string ""
1787 * is considered to occur at the index value {@code this.length()}.
1789 * <p>The returned index is the largest value <i>k</i> for which:
1791 * this.startsWith(str, <i>k</i>)
1792 * </pre></blockquote>
1793 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1795 * @param str the substring to search for.
1796 * @return the index of the last occurrence of the specified substring,
1797 * or {@code -1} if there is no such occurrence.
1799 public int lastIndexOf(String str) {
1800 return lastIndexOf(str, length());
1804 * Returns the index within this string of the last occurrence of the
1805 * specified substring, searching backward starting at the specified index.
1807 * <p>The returned index is the largest value <i>k</i> for which:
1809 * <i>k</i> <= fromIndex && this.startsWith(str, <i>k</i>)
1810 * </pre></blockquote>
1811 * If no such value of <i>k</i> exists, then {@code -1} is returned.
1813 * @param str the substring to search for.
1814 * @param fromIndex the index to start the search from.
1815 * @return the index of the last occurrence of the specified substring,
1816 * searching backward from the specified index,
1817 * or {@code -1} if there is no such occurrence.
1819 @JavaScriptBody(args = { "s", "from" }, body =
1820 "return this.toString().lastIndexOf(s.toString(), from);"
1822 public int lastIndexOf(String str, int fromIndex) {
1823 return lastIndexOf(toCharArray(), offset(), length(), str.toCharArray(), str.offset(), str.length(), fromIndex);
1827 * Code shared by String and StringBuffer to do searches. The
1828 * source is the character array being searched, and the target
1829 * is the string being searched for.
1831 * @param source the characters being searched.
1832 * @param sourceOffset offset of the source string.
1833 * @param sourceCount count of the source string.
1834 * @param target the characters being searched for.
1835 * @param targetOffset offset of the target string.
1836 * @param targetCount count of the target string.
1837 * @param fromIndex the index to begin searching from.
1839 static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
1840 char[] target, int targetOffset, int targetCount,
1843 * Check arguments; return immediately where possible. For
1844 * consistency, don't check for null str.
1846 int rightIndex = sourceCount - targetCount;
1847 if (fromIndex < 0) {
1850 if (fromIndex > rightIndex) {
1851 fromIndex = rightIndex;
1853 /* Empty string always matches. */
1854 if (targetCount == 0) {
1858 int strLastIndex = targetOffset + targetCount - 1;
1859 char strLastChar = target[strLastIndex];
1860 int min = sourceOffset + targetCount - 1;
1861 int i = min + fromIndex;
1863 startSearchForLastChar:
1865 while (i >= min && source[i] != strLastChar) {
1872 int start = j - (targetCount - 1);
1873 int k = strLastIndex - 1;
1876 if (source[j--] != target[k--]) {
1878 continue startSearchForLastChar;
1881 return start - sourceOffset + 1;
1886 * Returns a new string that is a substring of this string. The
1887 * substring begins with the character at the specified index and
1888 * extends to the end of this string. <p>
1891 * "unhappy".substring(2) returns "happy"
1892 * "Harbison".substring(3) returns "bison"
1893 * "emptiness".substring(9) returns "" (an empty string)
1894 * </pre></blockquote>
1896 * @param beginIndex the beginning index, inclusive.
1897 * @return the specified substring.
1898 * @exception IndexOutOfBoundsException if
1899 * <code>beginIndex</code> is negative or larger than the
1900 * length of this <code>String</code> object.
1902 public String substring(int beginIndex) {
1903 return substring(beginIndex, length());
1907 * Returns a new string that is a substring of this string. The
1908 * substring begins at the specified <code>beginIndex</code> and
1909 * extends to the character at index <code>endIndex - 1</code>.
1910 * Thus the length of the substring is <code>endIndex-beginIndex</code>.
1914 * "hamburger".substring(4, 8) returns "urge"
1915 * "smiles".substring(1, 5) returns "mile"
1916 * </pre></blockquote>
1918 * @param beginIndex the beginning index, inclusive.
1919 * @param endIndex the ending index, exclusive.
1920 * @return the specified substring.
1921 * @exception IndexOutOfBoundsException if the
1922 * <code>beginIndex</code> is negative, or
1923 * <code>endIndex</code> is larger than the length of
1924 * this <code>String</code> object, or
1925 * <code>beginIndex</code> is larger than
1926 * <code>endIndex</code>.
1928 @JavaScriptBody(args = { "beginIndex", "endIndex" }, body =
1929 "return this.toString().substring(beginIndex, endIndex);"
1931 public String substring(int beginIndex, int endIndex) {
1932 if (beginIndex < 0) {
1933 throw new StringIndexOutOfBoundsException(beginIndex);
1935 if (endIndex > length()) {
1936 throw new StringIndexOutOfBoundsException(endIndex);
1938 if (beginIndex > endIndex) {
1939 throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
1941 return ((beginIndex == 0) && (endIndex == length())) ? this :
1942 new String(toCharArray(), offset() + beginIndex, endIndex - beginIndex);
1946 * Returns a new character sequence that is a subsequence of this sequence.
1948 * <p> An invocation of this method of the form
1951 * str.subSequence(begin, end)</pre></blockquote>
1953 * behaves in exactly the same way as the invocation
1956 * str.substring(begin, end)</pre></blockquote>
1958 * This method is defined so that the <tt>String</tt> class can implement
1959 * the {@link CharSequence} interface. </p>
1961 * @param beginIndex the begin index, inclusive.
1962 * @param endIndex the end index, exclusive.
1963 * @return the specified subsequence.
1965 * @throws IndexOutOfBoundsException
1966 * if <tt>beginIndex</tt> or <tt>endIndex</tt> are negative,
1967 * if <tt>endIndex</tt> is greater than <tt>length()</tt>,
1968 * or if <tt>beginIndex</tt> is greater than <tt>startIndex</tt>
1973 public CharSequence subSequence(int beginIndex, int endIndex) {
1974 return this.substring(beginIndex, endIndex);
1978 * Concatenates the specified string to the end of this string.
1980 * If the length of the argument string is <code>0</code>, then this
1981 * <code>String</code> object is returned. Otherwise, a new
1982 * <code>String</code> object is created, representing a character
1983 * sequence that is the concatenation of the character sequence
1984 * represented by this <code>String</code> object and the character
1985 * sequence represented by the argument string.<p>
1988 * "cares".concat("s") returns "caress"
1989 * "to".concat("get").concat("her") returns "together"
1990 * </pre></blockquote>
1992 * @param str the <code>String</code> that is concatenated to the end
1993 * of this <code>String</code>.
1994 * @return a string that represents the concatenation of this object's
1995 * characters followed by the string argument's characters.
1997 public String concat(String str) {
1998 int otherLen = str.length();
1999 if (otherLen == 0) {
2002 char buf[] = new char[length() + otherLen];
2003 getChars(0, length(), buf, 0);
2004 str.getChars(0, otherLen, buf, length());
2005 return new String(buf, 0, length() + otherLen);
2009 * Returns a new string resulting from replacing all occurrences of
2010 * <code>oldChar</code> in this string with <code>newChar</code>.
2012 * If the character <code>oldChar</code> does not occur in the
2013 * character sequence represented by this <code>String</code> object,
2014 * then a reference to this <code>String</code> object is returned.
2015 * Otherwise, a new <code>String</code> object is created that
2016 * represents a character sequence identical to the character sequence
2017 * represented by this <code>String</code> object, except that every
2018 * occurrence of <code>oldChar</code> is replaced by an occurrence
2019 * of <code>newChar</code>.
2023 * "mesquite in your cellar".replace('e', 'o')
2024 * returns "mosquito in your collar"
2025 * "the war of baronets".replace('r', 'y')
2026 * returns "the way of bayonets"
2027 * "sparring with a purple porpoise".replace('p', 't')
2028 * returns "starring with a turtle tortoise"
2029 * "JonL".replace('q', 'x') returns "JonL" (no change)
2030 * </pre></blockquote>
2032 * @param oldChar the old character.
2033 * @param newChar the new character.
2034 * @return a string derived from this string by replacing every
2035 * occurrence of <code>oldChar</code> with <code>newChar</code>.
2037 @JavaScriptBody(args = { "arg1", "arg2" }, body =
2038 "if (typeof arg1 === 'number') arg1 = String.fromCharCode(arg1);\n" +
2039 "if (typeof arg2 === 'number') arg2 = String.fromCharCode(arg2);\n" +
2040 "var s = this.toString();\n" +
2042 " var ret = s.replace(arg1, arg2);\n" +
2043 " if (ret === s) {\n" +
2049 public String replace(char oldChar, char newChar) {
2050 if (oldChar != newChar) {
2053 char[] val = toCharArray(); /* avoid getfield opcode */
2054 int off = offset(); /* avoid getfield opcode */
2057 if (val[off + i] == oldChar) {
2062 char buf[] = new char[len];
2063 for (int j = 0 ; j < i ; j++) {
2064 buf[j] = val[off+j];
2067 char c = val[off + i];
2068 buf[i] = (c == oldChar) ? newChar : c;
2071 return new String(buf, 0, len);
2078 * Tells whether or not this string matches the given <a
2079 * href="../util/regex/Pattern.html#sum">regular expression</a>.
2081 * <p> An invocation of this method of the form
2082 * <i>str</i><tt>.matches(</tt><i>regex</i><tt>)</tt> yields exactly the
2083 * same result as the expression
2085 * <blockquote><tt> {@link java.util.regex.Pattern}.{@link
2086 * java.util.regex.Pattern#matches(String,CharSequence)
2087 * matches}(</tt><i>regex</i><tt>,</tt> <i>str</i><tt>)</tt></blockquote>
2090 * the regular expression to which this string is to be matched
2092 * @return <tt>true</tt> if, and only if, this string matches the
2093 * given regular expression
2095 * @throws PatternSyntaxException
2096 * if the regular expression's syntax is invalid
2098 * @see java.util.regex.Pattern
2103 public boolean matches(String regex) {
2105 return matchesViaJS(regex);
2106 } catch (Throwable t) {
2107 // fallback to classical behavior
2109 Method m = Class.forName("java.util.regex.Pattern").getMethod("matches", String.class, CharSequence.class);
2110 return (Boolean)m.invoke(null, regex, this);
2111 } catch (InvocationTargetException ex) {
2112 if (ex.getTargetException() instanceof RuntimeException) {
2113 throw (RuntimeException)ex.getTargetException();
2115 } catch (Throwable another) {
2116 // will report the old one
2118 throw new RuntimeException(t);
2121 @JavaScriptBody(args = { "regex" }, body =
2122 "var self = this.toString();\n"
2123 + "var re = new RegExp(regex.toString());\n"
2124 + "var r = re.exec(self);\n"
2125 + "return r != null && r.length > 0 && self.length == r[0].length;"
2127 private boolean matchesViaJS(String regex) {
2128 throw new UnsupportedOperationException();
2132 * Returns true if and only if this string contains the specified
2133 * sequence of char values.
2135 * @param s the sequence to search for
2136 * @return true if this string contains <code>s</code>, false otherwise
2137 * @throws NullPointerException if <code>s</code> is <code>null</code>
2140 public boolean contains(CharSequence s) {
2141 return indexOf(s.toString()) > -1;
2145 * Replaces the first substring of this string that matches the given <a
2146 * href="../util/regex/Pattern.html#sum">regular expression</a> with the
2147 * given replacement.
2149 * <p> An invocation of this method of the form
2150 * <i>str</i><tt>.replaceFirst(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt>
2151 * yields exactly the same result as the expression
2154 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2155 * compile}(</tt><i>regex</i><tt>).{@link
2156 * java.util.regex.Pattern#matcher(java.lang.CharSequence)
2157 * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceFirst
2158 * replaceFirst}(</tt><i>repl</i><tt>)</tt></blockquote>
2161 * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the
2162 * replacement string may cause the results to be different than if it were
2163 * being treated as a literal replacement string; see
2164 * {@link java.util.regex.Matcher#replaceFirst}.
2165 * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
2166 * meaning of these characters, if desired.
2169 * the regular expression to which this string is to be matched
2170 * @param replacement
2171 * the string to be substituted for the first match
2173 * @return The resulting <tt>String</tt>
2175 * @throws PatternSyntaxException
2176 * if the regular expression's syntax is invalid
2178 * @see java.util.regex.Pattern
2183 @JavaScriptBody(args = { "regex", "newText" }, body =
2184 "var self = this.toString();\n"
2185 + "var re = new RegExp(regex.toString());\n"
2186 + "var r = re.exec(self);\n"
2187 + "if (r === null || r.length === 0) return this;\n"
2188 + "var from = self.indexOf(r[0]);\n"
2189 + "return this.substring(0, from) + newText + this.substring(from + r[0].length);\n"
2191 public String replaceFirst(String regex, String replacement) {
2192 throw new UnsupportedOperationException();
2196 * Replaces each substring of this string that matches the given <a
2197 * href="../util/regex/Pattern.html#sum">regular expression</a> with the
2198 * given replacement.
2200 * <p> An invocation of this method of the form
2201 * <i>str</i><tt>.replaceAll(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt>
2202 * yields exactly the same result as the expression
2205 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2206 * compile}(</tt><i>regex</i><tt>).{@link
2207 * java.util.regex.Pattern#matcher(java.lang.CharSequence)
2208 * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceAll
2209 * replaceAll}(</tt><i>repl</i><tt>)</tt></blockquote>
2212 * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the
2213 * replacement string may cause the results to be different than if it were
2214 * being treated as a literal replacement string; see
2215 * {@link java.util.regex.Matcher#replaceAll Matcher.replaceAll}.
2216 * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
2217 * meaning of these characters, if desired.
2220 * the regular expression to which this string is to be matched
2221 * @param replacement
2222 * the string to be substituted for each match
2224 * @return The resulting <tt>String</tt>
2226 * @throws PatternSyntaxException
2227 * if the regular expression's syntax is invalid
2229 * @see java.util.regex.Pattern
2234 public String replaceAll(String regex, String replacement) {
2237 String n = p.replaceFirst(regex, replacement);
2246 * Replaces each substring of this string that matches the literal target
2247 * sequence with the specified literal replacement sequence. The
2248 * replacement proceeds from the beginning of the string to the end, for
2249 * example, replacing "aa" with "b" in the string "aaa" will result in
2250 * "ba" rather than "ab".
2252 * @param target The sequence of char values to be replaced
2253 * @param replacement The replacement sequence of char values
2254 * @return The resulting string
2255 * @throws NullPointerException if <code>target</code> or
2256 * <code>replacement</code> is <code>null</code>.
2259 @JavaScriptBody(args = { "target", "replacement" }, body =
2260 "var s = this.toString();\n"
2261 + "target = target.toString();\n"
2262 + "replacement = replacement.toString();\n"
2265 + " var indx = s.indexOf(target, pos);\n"
2266 + " if (indx === -1) {\n"
2269 + " pos = indx + replacement.length;\n"
2270 + " s = s.substring(0, indx) + replacement + s.substring(indx + target.length);\n"
2273 public native String replace(CharSequence target, CharSequence replacement);
2276 * Splits this string around matches of the given
2277 * <a href="../util/regex/Pattern.html#sum">regular expression</a>.
2279 * <p> The array returned by this method contains each substring of this
2280 * string that is terminated by another substring that matches the given
2281 * expression or is terminated by the end of the string. The substrings in
2282 * the array are in the order in which they occur in this string. If the
2283 * expression does not match any part of the input then the resulting array
2284 * has just one element, namely this string.
2286 * <p> The <tt>limit</tt> parameter controls the number of times the
2287 * pattern is applied and therefore affects the length of the resulting
2288 * array. If the limit <i>n</i> is greater than zero then the pattern
2289 * will be applied at most <i>n</i> - 1 times, the array's
2290 * length will be no greater than <i>n</i>, and the array's last entry
2291 * will contain all input beyond the last matched delimiter. If <i>n</i>
2292 * is non-positive then the pattern will be applied as many times as
2293 * possible and the array can have any length. If <i>n</i> is zero then
2294 * the pattern will be applied as many times as possible, the array can
2295 * have any length, and trailing empty strings will be discarded.
2297 * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the
2298 * following results with these parameters:
2300 * <blockquote><table cellpadding=1 cellspacing=0 summary="Split example showing regex, limit, and result">
2306 * <tr><td align=center>:</td>
2307 * <td align=center>2</td>
2308 * <td><tt>{ "boo", "and:foo" }</tt></td></tr>
2309 * <tr><td align=center>:</td>
2310 * <td align=center>5</td>
2311 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2312 * <tr><td align=center>:</td>
2313 * <td align=center>-2</td>
2314 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2315 * <tr><td align=center>o</td>
2316 * <td align=center>5</td>
2317 * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
2318 * <tr><td align=center>o</td>
2319 * <td align=center>-2</td>
2320 * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
2321 * <tr><td align=center>o</td>
2322 * <td align=center>0</td>
2323 * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
2324 * </table></blockquote>
2326 * <p> An invocation of this method of the form
2327 * <i>str.</i><tt>split(</tt><i>regex</i><tt>,</tt> <i>n</i><tt>)</tt>
2328 * yields the same result as the expression
2331 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2332 * compile}<tt>(</tt><i>regex</i><tt>)</tt>.{@link
2333 * java.util.regex.Pattern#split(java.lang.CharSequence,int)
2334 * split}<tt>(</tt><i>str</i><tt>,</tt> <i>n</i><tt>)</tt>
2339 * the delimiting regular expression
2342 * the result threshold, as described above
2344 * @return the array of strings computed by splitting this string
2345 * around matches of the given regular expression
2347 * @throws PatternSyntaxException
2348 * if the regular expression's syntax is invalid
2350 * @see java.util.regex.Pattern
2355 public String[] split(String regex, int limit) {
2357 Object[] arr = splitImpl(this, regex, Integer.MAX_VALUE);
2358 int to = arr.length;
2359 if (limit == 0 && to > 0) {
2360 while (to > 0 && ((String)arr[--to]).isEmpty()) {
2364 String[] ret = new String[to];
2365 System.arraycopy(arr, 0, ret, 0, to);
2368 Object[] arr = splitImpl(this, regex, limit);
2369 String[] ret = new String[arr.length];
2371 for (int i = 0; i < arr.length; i++) {
2372 final String s = (String)arr[i];
2374 pos = indexOf(s, pos) + s.length();
2376 ret[arr.length - 1] += substring(pos);
2381 @JavaScriptBody(args = { "str", "regex", "limit"}, body =
2382 "return str.split(new RegExp(regex), limit);"
2384 private static native Object[] splitImpl(String str, String regex, int limit);
2387 * Splits this string around matches of the given <a
2388 * href="../util/regex/Pattern.html#sum">regular expression</a>.
2390 * <p> This method works as if by invoking the two-argument {@link
2391 * #split(String, int) split} method with the given expression and a limit
2392 * argument of zero. Trailing empty strings are therefore not included in
2393 * the resulting array.
2395 * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the following
2396 * results with these expressions:
2398 * <blockquote><table cellpadding=1 cellspacing=0 summary="Split examples showing regex and result">
2403 * <tr><td align=center>:</td>
2404 * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2405 * <tr><td align=center>o</td>
2406 * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
2407 * </table></blockquote>
2411 * the delimiting regular expression
2413 * @return the array of strings computed by splitting this string
2414 * around matches of the given regular expression
2416 * @throws PatternSyntaxException
2417 * if the regular expression's syntax is invalid
2419 * @see java.util.regex.Pattern
2424 public String[] split(String regex) {
2425 return split(regex, 0);
2429 * Converts all of the characters in this <code>String</code> to lower
2430 * case using the rules of the given <code>Locale</code>. Case mapping is based
2431 * on the Unicode Standard version specified by the {@link java.lang.Character Character}
2432 * class. Since case mappings are not always 1:1 char mappings, the resulting
2433 * <code>String</code> may be a different length than the original <code>String</code>.
2435 * Examples of lowercase mappings are in the following table:
2436 * <table border="1" summary="Lowercase mapping examples showing language code of locale, upper case, lower case, and description">
2438 * <th>Language Code of Locale</th>
2439 * <th>Upper Case</th>
2440 * <th>Lower Case</th>
2441 * <th>Description</th>
2444 * <td>tr (Turkish)</td>
2445 * <td>\u0130</td>
2446 * <td>\u0069</td>
2447 * <td>capital letter I with dot above -> small letter i</td>
2450 * <td>tr (Turkish)</td>
2451 * <td>\u0049</td>
2452 * <td>\u0131</td>
2453 * <td>capital letter I -> small letter dotless i </td>
2457 * <td>French Fries</td>
2458 * <td>french fries</td>
2459 * <td>lowercased all chars in String</td>
2463 * <td><img src="doc-files/capiota.gif" alt="capiota"><img src="doc-files/capchi.gif" alt="capchi">
2464 * <img src="doc-files/captheta.gif" alt="captheta"><img src="doc-files/capupsil.gif" alt="capupsil">
2465 * <img src="doc-files/capsigma.gif" alt="capsigma"></td>
2466 * <td><img src="doc-files/iota.gif" alt="iota"><img src="doc-files/chi.gif" alt="chi">
2467 * <img src="doc-files/theta.gif" alt="theta"><img src="doc-files/upsilon.gif" alt="upsilon">
2468 * <img src="doc-files/sigma1.gif" alt="sigma"></td>
2469 * <td>lowercased all chars in String</td>
2473 * @param locale use the case transformation rules for this locale
2474 * @return the <code>String</code>, converted to lowercase.
2475 * @see java.lang.String#toLowerCase()
2476 * @see java.lang.String#toUpperCase()
2477 * @see java.lang.String#toUpperCase(Locale)
2480 public String toLowerCase(java.util.Locale locale) {
2481 return toLowerCase();
2483 // if (locale == null) {
2484 // throw new NullPointerException();
2489 // /* Now check if there are any characters that need to be changed. */
2491 // for (firstUpper = 0 ; firstUpper < count; ) {
2492 // char c = value[offset+firstUpper];
2493 // if ((c >= Character.MIN_HIGH_SURROGATE) &&
2494 // (c <= Character.MAX_HIGH_SURROGATE)) {
2495 // int supplChar = codePointAt(firstUpper);
2496 // if (supplChar != Character.toLowerCase(supplChar)) {
2499 // firstUpper += Character.charCount(supplChar);
2501 // if (c != Character.toLowerCase(c)) {
2510 // char[] result = new char[count];
2511 // int resultOffset = 0; /* result may grow, so i+resultOffset
2512 // * is the write location in result */
2514 // /* Just copy the first few lowerCase characters. */
2515 // System.arraycopy(value, offset, result, 0, firstUpper);
2517 // String lang = locale.getLanguage();
2518 // boolean localeDependent =
2519 // (lang == "tr" || lang == "az" || lang == "lt");
2520 // char[] lowerCharArray;
2524 // for (int i = firstUpper; i < count; i += srcCount) {
2525 // srcChar = (int)value[offset+i];
2526 // if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
2527 // (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
2528 // srcChar = codePointAt(i);
2529 // srcCount = Character.charCount(srcChar);
2533 // if (localeDependent || srcChar == '\u03A3') { // GREEK CAPITAL LETTER SIGMA
2534 // lowerChar = ConditionalSpecialCasing.toLowerCaseEx(this, i, locale);
2535 // } else if (srcChar == '\u0130') { // LATIN CAPITAL LETTER I DOT
2536 // lowerChar = Character.ERROR;
2538 // lowerChar = Character.toLowerCase(srcChar);
2540 // if ((lowerChar == Character.ERROR) ||
2541 // (lowerChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
2542 // if (lowerChar == Character.ERROR) {
2543 // if (!localeDependent && srcChar == '\u0130') {
2545 // ConditionalSpecialCasing.toLowerCaseCharArray(this, i, Locale.ENGLISH);
2548 // ConditionalSpecialCasing.toLowerCaseCharArray(this, i, locale);
2550 // } else if (srcCount == 2) {
2551 // resultOffset += Character.toChars(lowerChar, result, i + resultOffset) - srcCount;
2554 // lowerCharArray = Character.toChars(lowerChar);
2557 // /* Grow result if needed */
2558 // int mapLen = lowerCharArray.length;
2559 // if (mapLen > srcCount) {
2560 // char[] result2 = new char[result.length + mapLen - srcCount];
2561 // System.arraycopy(result, 0, result2, 0,
2562 // i + resultOffset);
2563 // result = result2;
2565 // for (int x=0; x<mapLen; ++x) {
2566 // result[i+resultOffset+x] = lowerCharArray[x];
2568 // resultOffset += (mapLen - srcCount);
2570 // result[i+resultOffset] = (char)lowerChar;
2573 // return new String(0, count+resultOffset, result);
2577 * Converts all of the characters in this <code>String</code> to lower
2578 * case using the rules of the default locale. This is equivalent to calling
2579 * <code>toLowerCase(Locale.getDefault())</code>.
2581 * <b>Note:</b> This method is locale sensitive, and may produce unexpected
2582 * results if used for strings that are intended to be interpreted locale
2584 * Examples are programming language identifiers, protocol keys, and HTML
2586 * For instance, <code>"TITLE".toLowerCase()</code> in a Turkish locale
2587 * returns <code>"t\u005Cu0131tle"</code>, where '\u005Cu0131' is the
2588 * LATIN SMALL LETTER DOTLESS I character.
2589 * To obtain correct results for locale insensitive strings, use
2590 * <code>toLowerCase(Locale.ENGLISH)</code>.
2592 * @return the <code>String</code>, converted to lowercase.
2593 * @see java.lang.String#toLowerCase(Locale)
2595 @JavaScriptBody(args = {}, body = "return this.toLowerCase();")
2596 public String toLowerCase() {
2601 * Converts all of the characters in this <code>String</code> to upper
2602 * case using the rules of the given <code>Locale</code>. Case mapping is based
2603 * on the Unicode Standard version specified by the {@link java.lang.Character Character}
2604 * class. Since case mappings are not always 1:1 char mappings, the resulting
2605 * <code>String</code> may be a different length than the original <code>String</code>.
2607 * Examples of locale-sensitive and 1:M case mappings are in the following table.
2609 * <table border="1" summary="Examples of locale-sensitive and 1:M case mappings. Shows Language code of locale, lower case, upper case, and description.">
2611 * <th>Language Code of Locale</th>
2612 * <th>Lower Case</th>
2613 * <th>Upper Case</th>
2614 * <th>Description</th>
2617 * <td>tr (Turkish)</td>
2618 * <td>\u0069</td>
2619 * <td>\u0130</td>
2620 * <td>small letter i -> capital letter I with dot above</td>
2623 * <td>tr (Turkish)</td>
2624 * <td>\u0131</td>
2625 * <td>\u0049</td>
2626 * <td>small letter dotless i -> capital letter I</td>
2630 * <td>\u00df</td>
2631 * <td>\u0053 \u0053</td>
2632 * <td>small letter sharp s -> two letters: SS</td>
2636 * <td>Fahrvergnügen</td>
2637 * <td>FAHRVERGNÜGEN</td>
2641 * @param locale use the case transformation rules for this locale
2642 * @return the <code>String</code>, converted to uppercase.
2643 * @see java.lang.String#toUpperCase()
2644 * @see java.lang.String#toLowerCase()
2645 * @see java.lang.String#toLowerCase(Locale)
2648 public String toUpperCase(Locale locale) {
2649 return toUpperCase();
2651 /* not for javascript
2652 if (locale == null) {
2653 throw new NullPointerException();
2658 // Now check if there are any characters that need to be changed.
2660 for (firstLower = 0 ; firstLower < count; ) {
2661 int c = (int)value[offset+firstLower];
2663 if ((c >= Character.MIN_HIGH_SURROGATE) &&
2664 (c <= Character.MAX_HIGH_SURROGATE)) {
2665 c = codePointAt(firstLower);
2666 srcCount = Character.charCount(c);
2670 int upperCaseChar = Character.toUpperCaseEx(c);
2671 if ((upperCaseChar == Character.ERROR) ||
2672 (c != upperCaseChar)) {
2675 firstLower += srcCount;
2680 char[] result = new char[count]; /* may grow *
2681 int resultOffset = 0; /* result may grow, so i+resultOffset
2682 * is the write location in result *
2684 /* Just copy the first few upperCase characters. *
2685 System.arraycopy(value, offset, result, 0, firstLower);
2687 String lang = locale.getLanguage();
2688 boolean localeDependent =
2689 (lang == "tr" || lang == "az" || lang == "lt");
2690 char[] upperCharArray;
2694 for (int i = firstLower; i < count; i += srcCount) {
2695 srcChar = (int)value[offset+i];
2696 if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
2697 (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
2698 srcChar = codePointAt(i);
2699 srcCount = Character.charCount(srcChar);
2703 if (localeDependent) {
2704 upperChar = ConditionalSpecialCasing.toUpperCaseEx(this, i, locale);
2706 upperChar = Character.toUpperCaseEx(srcChar);
2708 if ((upperChar == Character.ERROR) ||
2709 (upperChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
2710 if (upperChar == Character.ERROR) {
2711 if (localeDependent) {
2713 ConditionalSpecialCasing.toUpperCaseCharArray(this, i, locale);
2715 upperCharArray = Character.toUpperCaseCharArray(srcChar);
2717 } else if (srcCount == 2) {
2718 resultOffset += Character.toChars(upperChar, result, i + resultOffset) - srcCount;
2721 upperCharArray = Character.toChars(upperChar);
2724 /* Grow result if needed *
2725 int mapLen = upperCharArray.length;
2726 if (mapLen > srcCount) {
2727 char[] result2 = new char[result.length + mapLen - srcCount];
2728 System.arraycopy(result, 0, result2, 0,
2732 for (int x=0; x<mapLen; ++x) {
2733 result[i+resultOffset+x] = upperCharArray[x];
2735 resultOffset += (mapLen - srcCount);
2737 result[i+resultOffset] = (char)upperChar;
2740 return new String(0, count+resultOffset, result);
2745 * Converts all of the characters in this <code>String</code> to upper
2746 * case using the rules of the default locale. This method is equivalent to
2747 * <code>toUpperCase(Locale.getDefault())</code>.
2749 * <b>Note:</b> This method is locale sensitive, and may produce unexpected
2750 * results if used for strings that are intended to be interpreted locale
2752 * Examples are programming language identifiers, protocol keys, and HTML
2754 * For instance, <code>"title".toUpperCase()</code> in a Turkish locale
2755 * returns <code>"T\u005Cu0130TLE"</code>, where '\u005Cu0130' is the
2756 * LATIN CAPITAL LETTER I WITH DOT ABOVE character.
2757 * To obtain correct results for locale insensitive strings, use
2758 * <code>toUpperCase(Locale.ENGLISH)</code>.
2760 * @return the <code>String</code>, converted to uppercase.
2761 * @see java.lang.String#toUpperCase(Locale)
2763 @JavaScriptBody(args = {}, body = "return this.toUpperCase();")
2764 public String toUpperCase() {
2769 * Returns a copy of the string, with leading and trailing whitespace
2772 * If this <code>String</code> object represents an empty character
2773 * sequence, or the first and last characters of character sequence
2774 * represented by this <code>String</code> object both have codes
2775 * greater than <code>'\u0020'</code> (the space character), then a
2776 * reference to this <code>String</code> object is returned.
2778 * Otherwise, if there is no character with a code greater than
2779 * <code>'\u0020'</code> in the string, then a new
2780 * <code>String</code> object representing an empty string is created
2783 * Otherwise, let <i>k</i> be the index of the first character in the
2784 * string whose code is greater than <code>'\u0020'</code>, and let
2785 * <i>m</i> be the index of the last character in the string whose code
2786 * is greater than <code>'\u0020'</code>. A new <code>String</code>
2787 * object is created, representing the substring of this string that
2788 * begins with the character at index <i>k</i> and ends with the
2789 * character at index <i>m</i>-that is, the result of
2790 * <code>this.substring(<i>k</i>, <i>m</i>+1)</code>.
2792 * This method may be used to trim whitespace (as defined above) from
2793 * the beginning and end of a string.
2795 * @return A copy of this string with leading and trailing white
2796 * space removed, or this string if it has no leading or
2797 * trailing white space.
2799 public String trim() {
2802 int off = offset(); /* avoid getfield opcode */
2803 char[] val = toCharArray(); /* avoid getfield opcode */
2805 while ((st < len) && (val[off + st] <= ' ')) {
2808 while ((st < len) && (val[off + len - 1] <= ' ')) {
2811 return ((st > 0) || (len < length())) ? substring(st, len) : this;
2815 * This object (which is already a string!) is itself returned.
2817 * @return the string itself.
2819 @JavaScriptBody(args = {}, body = "return this.toString();")
2820 public String toString() {
2825 * Converts this string to a new character array.
2827 * @return a newly allocated character array whose length is the length
2828 * of this string and whose contents are initialized to contain
2829 * the character sequence represented by this string.
2831 public char[] toCharArray() {
2832 char result[] = new char[length()];
2833 getChars(0, length(), result, 0);
2838 * Returns a formatted string using the specified format string and
2841 * <p> The locale always used is the one returned by {@link
2842 * java.util.Locale#getDefault() Locale.getDefault()}.
2845 * A <a href="../util/Formatter.html#syntax">format string</a>
2848 * Arguments referenced by the format specifiers in the format
2849 * string. If there are more arguments than format specifiers, the
2850 * extra arguments are ignored. The number of arguments is
2851 * variable and may be zero. The maximum number of arguments is
2852 * limited by the maximum dimension of a Java array as defined by
2853 * <cite>The Java™ Virtual Machine Specification</cite>.
2854 * The behaviour on a
2855 * <tt>null</tt> argument depends on the <a
2856 * href="../util/Formatter.html#syntax">conversion</a>.
2858 * @throws IllegalFormatException
2859 * If a format string contains an illegal syntax, a format
2860 * specifier that is incompatible with the given arguments,
2861 * insufficient arguments given the format string, or other
2862 * illegal conditions. For specification of all possible
2863 * formatting errors, see the <a
2864 * href="../util/Formatter.html#detail">Details</a> section of the
2865 * formatter class specification.
2867 * @throws NullPointerException
2868 * If the <tt>format</tt> is <tt>null</tt>
2870 * @return A formatted string
2872 * @see java.util.Formatter
2875 public static String format(String format, Object ... args) {
2876 return format((Locale)null, format, args);
2880 * Returns a formatted string using the specified locale, format string,
2884 * The {@linkplain java.util.Locale locale} to apply during
2885 * formatting. If <tt>l</tt> is <tt>null</tt> then no localization
2889 * A <a href="../util/Formatter.html#syntax">format string</a>
2892 * Arguments referenced by the format specifiers in the format
2893 * string. If there are more arguments than format specifiers, the
2894 * extra arguments are ignored. The number of arguments is
2895 * variable and may be zero. The maximum number of arguments is
2896 * limited by the maximum dimension of a Java array as defined by
2897 * <cite>The Java™ Virtual Machine Specification</cite>.
2898 * The behaviour on a
2899 * <tt>null</tt> argument depends on the <a
2900 * href="../util/Formatter.html#syntax">conversion</a>.
2902 * @throws IllegalFormatException
2903 * If a format string contains an illegal syntax, a format
2904 * specifier that is incompatible with the given arguments,
2905 * insufficient arguments given the format string, or other
2906 * illegal conditions. For specification of all possible
2907 * formatting errors, see the <a
2908 * href="../util/Formatter.html#detail">Details</a> section of the
2909 * formatter class specification
2911 * @throws NullPointerException
2912 * If the <tt>format</tt> is <tt>null</tt>
2914 * @return A formatted string
2916 * @see java.util.Formatter
2919 public static String format(Locale l, String format, Object ... args) {
2921 for (int i = 0; i < args.length; i++) {
2922 String v = args[i] == null ? "null" : args[i].toString();
2923 p = p.replaceFirst("%s", v);
2926 // return new Formatter(l).format(format, args).toString();
2930 * Returns the string representation of the <code>Object</code> argument.
2932 * @param obj an <code>Object</code>.
2933 * @return if the argument is <code>null</code>, then a string equal to
2934 * <code>"null"</code>; otherwise, the value of
2935 * <code>obj.toString()</code> is returned.
2936 * @see java.lang.Object#toString()
2938 public static String valueOf(Object obj) {
2939 return (obj == null) ? "null" : obj.toString();
2943 * Returns the string representation of the <code>char</code> array
2944 * argument. The contents of the character array are copied; subsequent
2945 * modification of the character array does not affect the newly
2948 * @param data a <code>char</code> array.
2949 * @return a newly allocated string representing the same sequence of
2950 * characters contained in the character array argument.
2952 public static String valueOf(char data[]) {
2953 return new String(data);
2957 * Returns the string representation of a specific subarray of the
2958 * <code>char</code> array argument.
2960 * The <code>offset</code> argument is the index of the first
2961 * character of the subarray. The <code>count</code> argument
2962 * specifies the length of the subarray. The contents of the subarray
2963 * are copied; subsequent modification of the character array does not
2964 * affect the newly created string.
2966 * @param data the character array.
2967 * @param offset the initial offset into the value of the
2968 * <code>String</code>.
2969 * @param count the length of the value of the <code>String</code>.
2970 * @return a string representing the sequence of characters contained
2971 * in the subarray of the character array argument.
2972 * @exception IndexOutOfBoundsException if <code>offset</code> is
2973 * negative, or <code>count</code> is negative, or
2974 * <code>offset+count</code> is larger than
2975 * <code>data.length</code>.
2977 public static String valueOf(char data[], int offset, int count) {
2978 return new String(data, offset, count);
2982 * Returns a String that represents the character sequence in the
2985 * @param data the character array.
2986 * @param offset initial offset of the subarray.
2987 * @param count length of the subarray.
2988 * @return a <code>String</code> that contains the characters of the
2989 * specified subarray of the character array.
2991 public static String copyValueOf(char data[], int offset, int count) {
2992 // All public String constructors now copy the data.
2993 return new String(data, offset, count);
2997 * Returns a String that represents the character sequence in the
3000 * @param data the character array.
3001 * @return a <code>String</code> that contains the characters of the
3004 public static String copyValueOf(char data[]) {
3005 return copyValueOf(data, 0, data.length);
3009 * Returns the string representation of the <code>boolean</code> argument.
3011 * @param b a <code>boolean</code>.
3012 * @return if the argument is <code>true</code>, a string equal to
3013 * <code>"true"</code> is returned; otherwise, a string equal to
3014 * <code>"false"</code> is returned.
3016 public static String valueOf(boolean b) {
3017 return b ? "true" : "false";
3021 * Returns the string representation of the <code>char</code>
3024 * @param c a <code>char</code>.
3025 * @return a string of length <code>1</code> containing
3026 * as its single character the argument <code>c</code>.
3028 public static String valueOf(char c) {
3030 return new String(data, 0, 1);
3034 * Returns the string representation of the <code>int</code> argument.
3036 * The representation is exactly the one returned by the
3037 * <code>Integer.toString</code> method of one argument.
3039 * @param i an <code>int</code>.
3040 * @return a string representation of the <code>int</code> argument.
3041 * @see java.lang.Integer#toString(int, int)
3043 public static String valueOf(int i) {
3044 return Integer.toString(i);
3048 * Returns the string representation of the <code>long</code> argument.
3050 * The representation is exactly the one returned by the
3051 * <code>Long.toString</code> method of one argument.
3053 * @param l a <code>long</code>.
3054 * @return a string representation of the <code>long</code> argument.
3055 * @see java.lang.Long#toString(long)
3057 public static String valueOf(long l) {
3058 return Long.toString(l);
3062 * Returns the string representation of the <code>float</code> argument.
3064 * The representation is exactly the one returned by the
3065 * <code>Float.toString</code> method of one argument.
3067 * @param f a <code>float</code>.
3068 * @return a string representation of the <code>float</code> argument.
3069 * @see java.lang.Float#toString(float)
3071 public static String valueOf(float f) {
3072 return Float.toString(f);
3076 * Returns the string representation of the <code>double</code> argument.
3078 * The representation is exactly the one returned by the
3079 * <code>Double.toString</code> method of one argument.
3081 * @param d a <code>double</code>.
3082 * @return a string representation of the <code>double</code> argument.
3083 * @see java.lang.Double#toString(double)
3085 public static String valueOf(double d) {
3086 return Double.toString(d);
3090 * Returns a canonical representation for the string object.
3092 * A pool of strings, initially empty, is maintained privately by the
3093 * class <code>String</code>.
3095 * When the intern method is invoked, if the pool already contains a
3096 * string equal to this <code>String</code> object as determined by
3097 * the {@link #equals(Object)} method, then the string from the pool is
3098 * returned. Otherwise, this <code>String</code> object is added to the
3099 * pool and a reference to this <code>String</code> object is returned.
3101 * It follows that for any two strings <code>s</code> and <code>t</code>,
3102 * <code>s.intern() == t.intern()</code> is <code>true</code>
3103 * if and only if <code>s.equals(t)</code> is <code>true</code>.
3105 * All literal strings and string-valued constant expressions are
3106 * interned. String literals are defined in section 3.10.5 of the
3107 * <cite>The Java™ Language Specification</cite>.
3109 * @return a string that has the same contents as this string, but is
3110 * guaranteed to be from a pool of unique strings.
3112 @JavaScriptBody(args = {}, body =
3113 "var s = this.toString().toString();\n" +
3114 "var i = String.intern || (String.intern = {})\n" +
3120 public native String intern();
3123 private static <T> T checkUTF8(T data, String charsetName)
3124 throws UnsupportedEncodingException {
3125 if (charsetName == null) {
3126 throw new NullPointerException("charsetName");
3128 if (!charsetName.equalsIgnoreCase("UTF-8")
3129 && !charsetName.equalsIgnoreCase("UTF8")) {
3130 throw new UnsupportedEncodingException(charsetName);
3135 private static int nextChar(byte[] arr, int[] index) throws IndexOutOfBoundsException {
3136 int c = arr[index[0]++] & 0xff;
3150 /* 110x xxxx 10xx xxxx*/
3151 int char2 = (int) arr[index[0]++];
3152 if ((char2 & 0xC0) != 0x80) {
3153 throw new IndexOutOfBoundsException("malformed input");
3155 return (((c & 0x1F) << 6) | (char2 & 0x3F));
3158 /* 1110 xxxx 10xx xxxx 10xx xxxx */
3159 int char2 = arr[index[0]++];
3160 int char3 = arr[index[0]++];
3161 if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80)) {
3162 throw new IndexOutOfBoundsException("malformed input");
3164 return (((c & 0x0F) << 12)
3165 | ((char2 & 0x3F) << 6)
3166 | ((char3 & 0x3F) << 0));
3169 /* 10xx xxxx, 1111 xxxx */
3170 throw new IndexOutOfBoundsException("malformed input");