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
27
import java.io.ObjectStreamField;
28
import java.io.UnsupportedEncodingException;
29
import java.nio.charset.Charset;
30
import java.util.ArrayList;
31
import java.util.Arrays;
32
import java.util.Comparator;
33
import java.util.Formatter;
34
import java.util.Locale;
35
import java.util.regex.Matcher;
36
import java.util.regex.Pattern;
37
import java.util.regex.PatternSyntaxException;
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
108
final class StringHelper
111
* Allocates a new {@code String} that contains characters from a subarray
112
* of the <a href="Character.html#unicode">Unicode code point</a> array
113
* argument. The {@code offset} argument is the index of the first code
114
* point of the subarray and the {@code count} argument specifies the
115
* length of the subarray. The contents of the subarray are converted to
116
* {@code char}s; subsequent modification of the {@code int} array does not
117
* affect the newly created string.
120
* Array that is the source of Unicode code points
128
* @throws IllegalArgumentException
129
* If any invalid Unicode code point is found in {@code
132
* @throws IndexOutOfBoundsException
133
* If the {@code offset} and {@code count} arguments index
134
* characters outside the bounds of the {@code codePoints} array
138
static String NewString(int[] codePoints, int offset, int count) {
140
throw new StringIndexOutOfBoundsException(offset);
143
throw new StringIndexOutOfBoundsException(count);
145
// Note: offset or count might be near -1>>>1.
146
if (offset > codePoints.length - count) {
147
throw new StringIndexOutOfBoundsException(offset + count);
150
final int end = offset + count;
152
// Pass 1: Compute precise size of char[]
154
for (int i = offset; i < end; i++) {
155
int c = codePoints[i];
156
if (Character.isBmpCodePoint(c))
158
else if (Character.isValidCodePoint(c))
160
else throw new IllegalArgumentException(Integer.toString(c));
163
// Pass 2: Allocate and fill in char[]
164
final char[] v = new char[n];
166
for (int i = offset, j = 0; i < end; i++, j++) {
167
int c = codePoints[i];
168
if (Character.isBmpCodePoint(c))
171
Character.toSurrogates(c, v, j++);
174
return new String(v);
178
* Allocates a new {@code String} constructed from a subarray of an array
179
* of 8-bit integer values.
181
* <p> The {@code offset} argument is the index of the first byte of the
182
* subarray, and the {@code count} argument specifies the length of the
185
* <p> Each {@code byte} in the subarray is converted to a {@code char} as
186
* specified in the method above.
188
* @deprecated This method does not properly convert bytes into characters.
189
* As of JDK 1.1, the preferred way to do this is via the
190
* {@code String} constructors that take a {@link
191
* java.nio.charset.Charset}, charset name, or that use the platform's
195
* The bytes to be converted to characters
198
* The top 8 bits of each 16-bit Unicode code unit
205
* @throws IndexOutOfBoundsException
206
* If the {@code offset} or {@code count} argument is invalid
208
* @see #String(byte[], int)
209
* @see #String(byte[], int, int, java.lang.String)
210
* @see #String(byte[], int, int, java.nio.charset.Charset)
211
* @see #String(byte[], int, int)
212
* @see #String(byte[], java.lang.String)
213
* @see #String(byte[], java.nio.charset.Charset)
214
* @see #String(byte[])
217
static String NewString(byte ascii[], int hibyte, int offset, int count) {
218
checkBounds(ascii, offset, count);
219
char value[] = new char[count];
222
for (int i = count; i-- > 0;) {
223
value[i] = (char)(ascii[i + offset] & 0xff);
227
for (int i = count; i-- > 0;) {
228
value[i] = (char)(hibyte | (ascii[i + offset] & 0xff));
231
return new String(value, 0, count);
235
* Allocates a new {@code String} containing characters constructed from
236
* an array of 8-bit integer values. Each character <i>c</i>in the
237
* resulting string is constructed from the corresponding component
238
* <i>b</i> in the byte array such that:
241
* <b><i>c</i></b> == (char)(((hibyte & 0xff) << 8)
242
* | (<b><i>b</i></b> & 0xff))
243
* </pre></blockquote>
245
* @deprecated This method does not properly convert bytes into
246
* characters. As of JDK 1.1, the preferred way to do this is via the
247
* {@code String} constructors that take a {@link
248
* java.nio.charset.Charset}, charset name, or that use the platform's
252
* The bytes to be converted to characters
255
* The top 8 bits of each 16-bit Unicode code unit
257
* @see #String(byte[], int, int, java.lang.String)
258
* @see #String(byte[], int, int, java.nio.charset.Charset)
259
* @see #String(byte[], int, int)
260
* @see #String(byte[], java.lang.String)
261
* @see #String(byte[], java.nio.charset.Charset)
262
* @see #String(byte[])
265
static String NewString(byte ascii[], int hibyte) {
266
return NewString(ascii, hibyte, 0, ascii.length);
269
/* Common private utility method used to bounds check the byte array
270
* and requested offset & length values used by the String(byte[],..)
273
private static void checkBounds(byte[] bytes, int offset, int length) {
275
throw new StringIndexOutOfBoundsException(length);
277
throw new StringIndexOutOfBoundsException(offset);
278
if (offset > bytes.length - length)
279
throw new StringIndexOutOfBoundsException(offset + length);
283
* Constructs a new {@code String} by decoding the specified subarray of
284
* bytes using the specified charset. The length of the new {@code String}
285
* is a function of the charset, and hence may not be equal to the length
288
* <p> The behavior of this constructor when the given bytes are not valid
289
* in the given charset is unspecified. The {@link
290
* java.nio.charset.CharsetDecoder} class should be used when more control
291
* over the decoding process is required.
294
* The bytes to be decoded into characters
297
* The index of the first byte to decode
300
* The number of bytes to decode
303
* The name of a supported {@linkplain java.nio.charset.Charset
306
* @throws UnsupportedEncodingException
307
* If the named charset is not supported
309
* @throws IndexOutOfBoundsException
310
* If the {@code offset} and {@code length} arguments index
311
* characters outside the bounds of the {@code bytes} array
315
static String NewString(byte bytes[], int offset, int length, String charsetName)
316
throws UnsupportedEncodingException {
317
if (charsetName == null)
318
throw new NullPointerException("charsetName");
319
checkBounds(bytes, offset, length);
320
char[] v = StringCoding.decode(charsetName, bytes, offset, length);
321
return new String(v);
325
* Constructs a new {@code String} by decoding the specified subarray of
326
* bytes using the specified {@linkplain java.nio.charset.Charset charset}.
327
* The length of the new {@code String} is a function of the charset, and
328
* hence may not be equal to the length of the subarray.
330
* <p> This method always replaces malformed-input and unmappable-character
331
* sequences with this charset's default replacement string. The {@link
332
* java.nio.charset.CharsetDecoder} class should be used when more control
333
* over the decoding process is required.
336
* The bytes to be decoded into characters
339
* The index of the first byte to decode
342
* The number of bytes to decode
345
* The {@linkplain java.nio.charset.Charset charset} to be used to
346
* decode the {@code bytes}
348
* @throws IndexOutOfBoundsException
349
* If the {@code offset} and {@code length} arguments index
350
* characters outside the bounds of the {@code bytes} array
354
static String NewString(byte bytes[], int offset, int length, Charset charset) {
356
throw new NullPointerException("charset");
357
checkBounds(bytes, offset, length);
358
char[] v = StringCoding.decode(charset, bytes, offset, length);
359
return new String(v);
363
* Constructs a new {@code String} by decoding the specified array of bytes
364
* using the specified {@linkplain java.nio.charset.Charset charset}. The
365
* length of the new {@code String} is a function of the charset, and hence
366
* may not be equal to the length of the byte array.
368
* <p> The behavior of this constructor when the given bytes are not valid
369
* in the given charset is unspecified. The {@link
370
* java.nio.charset.CharsetDecoder} class should be used when more control
371
* over the decoding process is required.
374
* The bytes to be decoded into characters
377
* The name of a supported {@linkplain java.nio.charset.Charset
380
* @throws UnsupportedEncodingException
381
* If the named charset is not supported
385
static String NewString(byte bytes[], String charsetName)
386
throws UnsupportedEncodingException {
387
return NewString(bytes, 0, bytes.length, charsetName);
391
* Constructs a new {@code String} by decoding the specified array of
392
* bytes using the specified {@linkplain java.nio.charset.Charset charset}.
393
* The length of the new {@code String} is a function of the charset, and
394
* hence may not be equal to the length of the byte array.
396
* <p> This method always replaces malformed-input and unmappable-character
397
* sequences with this charset's default replacement string. The {@link
398
* java.nio.charset.CharsetDecoder} class should be used when more control
399
* over the decoding process is required.
402
* The bytes to be decoded into characters
405
* The {@linkplain java.nio.charset.Charset charset} to be used to
406
* decode the {@code bytes}
410
static String NewString(byte bytes[], Charset charset) {
411
return NewString(bytes, 0, bytes.length, charset);
415
* Constructs a new {@code String} by decoding the specified subarray of
416
* bytes using the platform's default charset. The length of the new
417
* {@code String} is a function of the charset, and hence may not be equal
418
* to the length of the subarray.
420
* <p> The behavior of this constructor when the given bytes are not valid
421
* in the default charset is unspecified. The {@link
422
* java.nio.charset.CharsetDecoder} class should be used when more control
423
* over the decoding process is required.
426
* The bytes to be decoded into characters
429
* The index of the first byte to decode
432
* The number of bytes to decode
434
* @throws IndexOutOfBoundsException
435
* If the {@code offset} and the {@code length} arguments index
436
* characters outside the bounds of the {@code bytes} array
440
static String NewString(byte bytes[], int offset, int length) {
441
checkBounds(bytes, offset, length);
442
char[] v = StringCoding.decode(bytes, offset, length);
443
return new String(v);
447
* Constructs a new {@code String} by decoding the specified array of bytes
448
* using the platform's default charset. The length of the new {@code
449
* String} is a function of the charset, and hence may not be equal to the
450
* length of the byte array.
452
* <p> The behavior of this constructor when the given bytes are not valid
453
* in the default charset is unspecified. The {@link
454
* java.nio.charset.CharsetDecoder} class should be used when more control
455
* over the decoding process is required.
458
* The bytes to be decoded into characters
462
static String NewString(byte bytes[]) {
463
return NewString(bytes, 0, bytes.length);
467
* Allocates a new string that contains the sequence of characters
468
* currently contained in the string buffer argument. The contents of the
469
* string buffer are copied; subsequent modification of the string buffer
470
* does not affect the newly created string.
473
* A {@code StringBuffer}
475
static String NewString(StringBuffer buffer) {
476
return buffer.toString();
480
* Allocates a new string that contains the sequence of characters
481
* currently contained in the string builder argument. The contents of the
482
* string builder are copied; subsequent modification of the string builder
483
* does not affect the newly created string.
485
* <p> This constructor is provided to ease migration to {@code
486
* StringBuilder}. Obtaining a string from a string builder via the {@code
487
* toString} method is likely to run faster and is generally preferred.
490
* A {@code StringBuilder}
494
static String NewString(StringBuilder builder) {
495
return builder.toString();
499
// Package private constructor which shares value array for speed.
500
static String NewString(int offset, int count, char value[]) {
501
return new String(value, offset, count);
505
* Returns the character (Unicode code point) at the specified
506
* index. The index refers to <code>char</code> values
507
* (Unicode code units) and ranges from <code>0</code> to
508
* {@link #length()}<code> - 1</code>.
510
* <p> If the <code>char</code> value specified at the given index
511
* is in the high-surrogate range, the following index is less
512
* than the length of this <code>String</code>, and the
513
* <code>char</code> value at the following index is in the
514
* low-surrogate range, then the supplementary code point
515
* corresponding to this surrogate pair is returned. Otherwise,
516
* the <code>char</code> value at the given index is returned.
518
* @param index the index to the <code>char</code> values
519
* @return the code point value of the character at the
521
* @exception IndexOutOfBoundsException if the <code>index</code>
522
* argument is negative or not less than the length of this
526
static int codePointAt(String _this, int index) {
527
if ((index < 0) || (index >= _this.length())) {
528
throw new StringIndexOutOfBoundsException(index);
530
char c1 = _this.charAt(index++);
531
if (Character.isHighSurrogate(c1)) {
532
if (index < _this.length()) {
533
char c2 = _this.charAt(index);
534
if (Character.isLowSurrogate(c2)) {
535
return Character.toCodePoint(c1, c2);
543
* Returns the character (Unicode code point) before the specified
544
* index. The index refers to <code>char</code> values
545
* (Unicode code units) and ranges from <code>1</code> to {@link
546
* CharSequence#length() length}.
548
* <p> If the <code>char</code> value at <code>(index - 1)</code>
549
* is in the low-surrogate range, <code>(index - 2)</code> is not
550
* negative, and the <code>char</code> value at <code>(index -
551
* 2)</code> is in the high-surrogate range, then the
552
* supplementary code point value of the surrogate pair is
553
* returned. If the <code>char</code> value at <code>index -
554
* 1</code> is an unpaired low-surrogate or a high-surrogate, the
555
* surrogate value is returned.
557
* @param index the index following the code point that should be returned
558
* @return the Unicode code point value before the given index.
559
* @exception IndexOutOfBoundsException if the <code>index</code>
560
* argument is less than 1 or greater than the length
564
static int codePointBefore(String _this, int index) {
566
if ((i < 0) || (i >= _this.length())) {
567
throw new StringIndexOutOfBoundsException(index);
569
char c2 = _this.charAt(--index);
570
if (Character.isLowSurrogate(c2)) {
572
char c1 = _this.charAt(--index);
573
if (Character.isHighSurrogate(c1)) {
574
return Character.toCodePoint(c1, c2);
582
* Returns the number of Unicode code points in the specified text
583
* range of this <code>String</code>. The text range begins at the
584
* specified <code>beginIndex</code> and extends to the
585
* <code>char</code> at index <code>endIndex - 1</code>. Thus the
586
* length (in <code>char</code>s) of the text range is
587
* <code>endIndex-beginIndex</code>. Unpaired surrogates within
588
* the text range count as one code point each.
590
* @param beginIndex the index to the first <code>char</code> of
592
* @param endIndex the index after the last <code>char</code> of
594
* @return the number of Unicode code points in the specified text
596
* @exception IndexOutOfBoundsException if the
597
* <code>beginIndex</code> is negative, or <code>endIndex</code>
598
* is larger than the length of this <code>String</code>, or
599
* <code>beginIndex</code> is larger than <code>endIndex</code>.
602
static int codePointCount(String _this, int beginIndex, int endIndex) {
603
if (beginIndex < 0 || endIndex > _this.length() || beginIndex > endIndex) {
604
throw new IndexOutOfBoundsException();
607
for (int i = beginIndex; i < endIndex; ) {
609
if (Character.isHighSurrogate(_this.charAt(i++))) {
610
if (i < endIndex && Character.isLowSurrogate(_this.charAt(i))) {
619
* Returns the index within this <code>String</code> that is
620
* offset from the given <code>index</code> by
621
* <code>codePointOffset</code> code points. Unpaired surrogates
622
* within the text range given by <code>index</code> and
623
* <code>codePointOffset</code> count as one code point each.
625
* @param index the index to be offset
626
* @param codePointOffset the offset in code points
627
* @return the index within this <code>String</code>
628
* @exception IndexOutOfBoundsException if <code>index</code>
629
* is negative or larger then the length of this
630
* <code>String</code>, or if <code>codePointOffset</code> is positive
631
* and the substring starting with <code>index</code> has fewer
632
* than <code>codePointOffset</code> code points,
633
* or if <code>codePointOffset</code> is negative and the substring
634
* before <code>index</code> has fewer than the absolute value
635
* of <code>codePointOffset</code> code points.
638
static int offsetByCodePoints(String _this, int index, int codePointOffset) {
639
int count = _this.length();
640
if (index < 0 || index > count) {
641
throw new IndexOutOfBoundsException();
644
if (codePointOffset >= 0) {
647
for (i = 0; x < limit && i < codePointOffset; i++) {
648
if (Character.isHighSurrogate(_this.charAt(x++))) {
649
if (x < limit && Character.isLowSurrogate(_this.charAt(x))) {
654
if (i < codePointOffset) {
655
throw new IndexOutOfBoundsException();
659
for (i = codePointOffset; x > 0 && i < 0; i++) {
660
if (Character.isLowSurrogate(_this.charAt(--x))) {
661
if (x > 0 && Character.isHighSurrogate(_this.charAt(x-1))) {
667
throw new IndexOutOfBoundsException();
674
* Copy characters from this string into dst starting at dstBegin.
675
* This method doesn't perform any range checking.
677
static void getChars(String _this, char dst[], int dstBegin) {
678
_this.getChars(0, _this.length(), dst, dstBegin);
682
* Copies characters from this string into the destination character
685
* The first character to be copied is at index <code>srcBegin</code>;
686
* the last character to be copied is at index <code>srcEnd-1</code>
687
* (thus the total number of characters to be copied is
688
* <code>srcEnd-srcBegin</code>). The characters are copied into the
689
* subarray of <code>dst</code> starting at index <code>dstBegin</code>
690
* and ending at index:
691
* <p><blockquote><pre>
692
* dstbegin + (srcEnd-srcBegin) - 1
693
* </pre></blockquote>
695
* @param srcBegin index of the first character in the string
697
* @param srcEnd index after the last character in the string
699
* @param dst the destination array.
700
* @param dstBegin the start offset in the destination array.
701
* @exception IndexOutOfBoundsException If any of the following
703
* <ul><li><code>srcBegin</code> is negative.
704
* <li><code>srcBegin</code> is greater than <code>srcEnd</code>
705
* <li><code>srcEnd</code> is greater than the length of this
707
* <li><code>dstBegin</code> is negative
708
* <li><code>dstBegin+(srcEnd-srcBegin)</code> is larger than
709
* <code>dst.length</code></ul>
711
static void getChars(cli.System.String _this, int srcBegin, int srcEnd, char dst[], int dstBegin) {
713
throw new StringIndexOutOfBoundsException(srcBegin);
715
if (srcEnd > _this.get_Length()) {
716
throw new StringIndexOutOfBoundsException(srcEnd);
718
if (srcBegin > srcEnd) {
719
throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
721
_this.CopyTo(srcBegin, dst, dstBegin, srcEnd - srcBegin);
725
* Copies characters from this string into the destination byte array. Each
726
* byte receives the 8 low-order bits of the corresponding character. The
727
* eight high-order bits of each character are not copied and do not
728
* participate in the transfer in any way.
730
* <p> The first character to be copied is at index {@code srcBegin}; the
731
* last character to be copied is at index {@code srcEnd-1}. The total
732
* number of characters to be copied is {@code srcEnd-srcBegin}. The
733
* characters, converted to bytes, are copied into the subarray of {@code
734
* dst} starting at index {@code dstBegin} and ending at index:
737
* dstbegin + (srcEnd-srcBegin) - 1
738
* </pre></blockquote>
740
* @deprecated This method does not properly convert characters into
741
* bytes. As of JDK 1.1, the preferred way to do this is via the
742
* {@link #getBytes()} method, which uses the platform's default charset.
745
* Index of the first character in the string to copy
748
* Index after the last character in the string to copy
751
* The destination array
754
* The start offset in the destination array
756
* @throws IndexOutOfBoundsException
757
* If any of the following is true:
759
* <li> {@code srcBegin} is negative
760
* <li> {@code srcBegin} is greater than {@code srcEnd}
761
* <li> {@code srcEnd} is greater than the length of this String
762
* <li> {@code dstBegin} is negative
763
* <li> {@code dstBegin+(srcEnd-srcBegin)} is larger than {@code
768
static void getBytes(String _this, int srcBegin, int srcEnd, byte dst[], int dstBegin) {
770
throw new StringIndexOutOfBoundsException(srcBegin);
772
if (srcEnd > _this.length()) {
773
throw new StringIndexOutOfBoundsException(srcEnd);
775
if (srcBegin > srcEnd) {
776
throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
783
dst[j++] = (byte)_this.charAt(i++);
788
* Encodes this {@code String} into a sequence of bytes using the named
789
* charset, storing the result into a new byte array.
791
* <p> The behavior of this method when this string cannot be encoded in
792
* the given charset is unspecified. The {@link
793
* java.nio.charset.CharsetEncoder} class should be used when more control
794
* over the encoding process is required.
797
* The name of a supported {@linkplain java.nio.charset.Charset
800
* @return The resultant byte array
802
* @throws UnsupportedEncodingException
803
* If the named charset is not supported
807
static byte[] getBytes(String _this, String charsetName)
808
throws UnsupportedEncodingException {
809
if (charsetName == null) throw new NullPointerException();
810
char[] value = _this.toCharArray();
811
return StringCoding.encode(charsetName, value, 0, value.length);
815
* Encodes this {@code String} into a sequence of bytes using the given
816
* {@linkplain java.nio.charset.Charset charset}, storing the result into a
819
* <p> This method always replaces malformed-input and unmappable-character
820
* sequences with this charset's default replacement byte array. The
821
* {@link java.nio.charset.CharsetEncoder} class should be used when more
822
* control over the encoding process is required.
825
* The {@linkplain java.nio.charset.Charset} to be used to encode
828
* @return The resultant byte array
832
static byte[] getBytes(String _this, Charset charset) {
833
if (charset == null) throw new NullPointerException();
834
char[] value = _this.toCharArray();
835
return StringCoding.encode(charset, value, 0, value.length);
839
* Encodes this {@code String} into a sequence of bytes using the
840
* platform's default charset, storing the result into a new byte array.
842
* <p> The behavior of this method when this string cannot be encoded in
843
* the default charset is unspecified. The {@link
844
* java.nio.charset.CharsetEncoder} class should be used when more control
845
* over the encoding process is required.
847
* @return The resultant byte array
851
static byte[] getBytes(String _this) {
852
char[] value = _this.toCharArray();
853
return StringCoding.encode(value, 0, value.length);
857
* Compares this string to the specified {@code StringBuffer}. The result
858
* is {@code true} if and only if this {@code String} represents the same
859
* sequence of characters as the specified {@code StringBuffer}.
862
* The {@code StringBuffer} to compare this {@code String} against
864
* @return {@code true} if this {@code String} represents the same
865
* sequence of characters as the specified {@code StringBuffer},
866
* {@code false} otherwise
870
static boolean contentEquals(String _this, StringBuffer sb) {
872
return contentEquals(_this, (CharSequence) sb);
877
* Compares this string to the specified {@code CharSequence}. The result
878
* is {@code true} if and only if this {@code String} represents the same
879
* sequence of char values as the specified sequence.
882
* The sequence to compare this {@code String} against
884
* @return {@code true} if this {@code String} represents the same
885
* sequence of char values as the specified sequence, {@code
890
static boolean contentEquals(String _this, CharSequence cs) {
891
if (_this.length() != cs.length())
893
// Argument is a StringBuffer, StringBuilder
894
if (cs instanceof AbstractStringBuilder) {
895
char v2[] = ((AbstractStringBuilder) cs).getValue();
897
int n = _this.length();
899
if (_this.charAt(i) != v2[i])
905
// Argument is a String
906
if (cs.equals(_this))
908
// Argument is a generic CharSequence
910
int n = _this.length();
912
if (_this.charAt(i) != cs.charAt(i))
920
* Compares this {@code String} to another {@code String}, ignoring case
921
* considerations. Two strings are considered equal ignoring case if they
922
* are of the same length and corresponding characters in the two strings
923
* are equal ignoring case.
925
* <p> Two characters {@code c1} and {@code c2} are considered the same
926
* ignoring case if at least one of the following is true:
928
* <li> The two characters are the same (as compared by the
929
* {@code ==} operator)
930
* <li> Applying the method {@link
931
* java.lang.Character#toUpperCase(char)} to each character
932
* produces the same result
933
* <li> Applying the method {@link
934
* java.lang.Character#toLowerCase(char)} to each character
935
* produces the same result
938
* @param anotherString
939
* The {@code String} to compare this {@code String} against
941
* @return {@code true} if the argument is not {@code null} and it
942
* represents an equivalent {@code String} ignoring case; {@code
945
* @see #equals(Object)
947
static boolean equalsIgnoreCase(String _this, String anotherString) {
948
return (_this == anotherString) ? true
949
: (anotherString != null)
950
&& (anotherString.length() == _this.length())
951
&& regionMatches(_this, true, 0, anotherString, 0, _this.length());
955
* Compares two strings lexicographically.
956
* The comparison is based on the Unicode value of each character in
957
* the strings. The character sequence represented by this
958
* <code>String</code> object is compared lexicographically to the
959
* character sequence represented by the argument string. The result is
960
* a negative integer if this <code>String</code> object
961
* lexicographically precedes the argument string. The result is a
962
* positive integer if this <code>String</code> object lexicographically
963
* follows the argument string. The result is zero if the strings
964
* are equal; <code>compareTo</code> returns <code>0</code> exactly when
965
* the {@link #equals(Object)} method would return <code>true</code>.
967
* This is the definition of lexicographic ordering. If two strings are
968
* different, then either they have different characters at some index
969
* that is a valid index for both strings, or their lengths are different,
970
* or both. If they have different characters at one or more index
971
* positions, let <i>k</i> be the smallest such index; then the string
972
* whose character at position <i>k</i> has the smaller value, as
973
* determined by using the < operator, lexicographically precedes the
974
* other string. In this case, <code>compareTo</code> returns the
975
* difference of the two character values at position <code>k</code> in
976
* the two string -- that is, the value:
978
* this.charAt(k)-anotherString.charAt(k)
979
* </pre></blockquote>
980
* If there is no index position at which they differ, then the shorter
981
* string lexicographically precedes the longer string. In this case,
982
* <code>compareTo</code> returns the difference of the lengths of the
983
* strings -- that is, the value:
985
* this.length()-anotherString.length()
986
* </pre></blockquote>
988
* @param anotherString the <code>String</code> to be compared.
989
* @return the value <code>0</code> if the argument string is equal to
990
* this string; a value less than <code>0</code> if this string
991
* is lexicographically less than the string argument; and a
992
* value greater than <code>0</code> if this string is
993
* lexicographically greater than the string argument.
995
static int compareTo(String _this, String anotherString) {
996
int len = Math.min(_this.length(), anotherString.length());
997
for (int i = 0; i < len; i++)
999
int diff = _this.charAt(i) - anotherString.charAt(i);
1005
return _this.length() - anotherString.length();
1009
* Compares two strings lexicographically, ignoring case
1010
* differences. This method returns an integer whose sign is that of
1011
* calling <code>compareTo</code> with normalized versions of the strings
1012
* where case differences have been eliminated by calling
1013
* <code>Character.toLowerCase(Character.toUpperCase(character))</code> on
1016
* Note that this method does <em>not</em> take locale into account,
1017
* and will result in an unsatisfactory ordering for certain locales.
1018
* The java.text package provides <em>collators</em> to allow
1019
* locale-sensitive ordering.
1021
* @param str the <code>String</code> to be compared.
1022
* @return a negative integer, zero, or a positive integer as the
1023
* specified String is greater than, equal to, or less
1024
* than this String, ignoring case considerations.
1025
* @see java.text.Collator#compare(String, String)
1028
static int compareToIgnoreCase(String _this, String str) {
1029
return String.CASE_INSENSITIVE_ORDER.compare(_this, str);
1033
* Tests if two string regions are equal.
1035
* A substring of this <tt>String</tt> object is compared to a substring
1036
* of the argument other. The result is true if these substrings
1037
* represent identical character sequences. The substring of this
1038
* <tt>String</tt> object to be compared begins at index <tt>toffset</tt>
1039
* and has length <tt>len</tt>. The substring of other to be compared
1040
* begins at index <tt>ooffset</tt> and has length <tt>len</tt>. The
1041
* result is <tt>false</tt> if and only if at least one of the following
1043
* <ul><li><tt>toffset</tt> is negative.
1044
* <li><tt>ooffset</tt> is negative.
1045
* <li><tt>toffset+len</tt> is greater than the length of this
1046
* <tt>String</tt> object.
1047
* <li><tt>ooffset+len</tt> is greater than the length of the other
1049
* <li>There is some nonnegative integer <i>k</i> less than <tt>len</tt>
1051
* <tt>this.charAt(toffset+<i>k</i>) != other.charAt(ooffset+<i>k</i>)</tt>
1054
* @param toffset the starting offset of the subregion in this string.
1055
* @param other the string argument.
1056
* @param ooffset the starting offset of the subregion in the string
1058
* @param len the number of characters to compare.
1059
* @return <code>true</code> if the specified subregion of this string
1060
* exactly matches the specified subregion of the string argument;
1061
* <code>false</code> otherwise.
1063
static boolean regionMatches(String _this, int toffset, String other, int ooffset,
1067
// Note: toffset, ooffset, or len might be near -1>>>1.
1068
if ((ooffset < 0) || (toffset < 0)
1069
|| (toffset > (long)_this.length() - len)
1070
|| (ooffset > (long)other.length() - len)) {
1074
if (_this.charAt(to++) != other.charAt(po++)) {
1082
* Tests if two string regions are equal.
1084
* A substring of this <tt>String</tt> object is compared to a substring
1085
* of the argument <tt>other</tt>. The result is <tt>true</tt> if these
1086
* substrings represent character sequences that are the same, ignoring
1087
* case if and only if <tt>ignoreCase</tt> is true. The substring of
1088
* this <tt>String</tt> object to be compared begins at index
1089
* <tt>toffset</tt> and has length <tt>len</tt>. The substring of
1090
* <tt>other</tt> to be compared begins at index <tt>ooffset</tt> and
1091
* has length <tt>len</tt>. The result is <tt>false</tt> if and only if
1092
* at least one of the following is true:
1093
* <ul><li><tt>toffset</tt> is negative.
1094
* <li><tt>ooffset</tt> is negative.
1095
* <li><tt>toffset+len</tt> is greater than the length of this
1096
* <tt>String</tt> object.
1097
* <li><tt>ooffset+len</tt> is greater than the length of the other
1099
* <li><tt>ignoreCase</tt> is <tt>false</tt> and there is some nonnegative
1100
* integer <i>k</i> less than <tt>len</tt> such that:
1102
* this.charAt(toffset+k) != other.charAt(ooffset+k)
1103
* </pre></blockquote>
1104
* <li><tt>ignoreCase</tt> is <tt>true</tt> and there is some nonnegative
1105
* integer <i>k</i> less than <tt>len</tt> such that:
1107
* Character.toLowerCase(this.charAt(toffset+k)) !=
1108
Character.toLowerCase(other.charAt(ooffset+k))
1109
* </pre></blockquote>
1112
* Character.toUpperCase(this.charAt(toffset+k)) !=
1113
* Character.toUpperCase(other.charAt(ooffset+k))
1114
* </pre></blockquote>
1117
* @param ignoreCase if <code>true</code>, ignore case when comparing
1119
* @param toffset the starting offset of the subregion in this
1121
* @param other the string argument.
1122
* @param ooffset the starting offset of the subregion in the string
1124
* @param len the number of characters to compare.
1125
* @return <code>true</code> if the specified subregion of this string
1126
* matches the specified subregion of the string argument;
1127
* <code>false</code> otherwise. Whether the matching is exact
1128
* or case insensitive depends on the <code>ignoreCase</code>
1131
static boolean regionMatches(String _this, boolean ignoreCase, int toffset,
1132
String other, int ooffset, int len) {
1135
// Note: toffset, ooffset, or len might be near -1>>>1.
1136
if ((ooffset < 0) || (toffset < 0)
1137
|| (toffset > (long)_this.length() - len)
1138
|| (ooffset > (long)other.length() - len)) {
1142
char c1 = _this.charAt(to++);
1143
char c2 = other.charAt(po++);
1148
// If characters don't match but case may be ignored,
1149
// try converting both characters to uppercase.
1150
// If the results match, then the comparison scan should
1152
char u1 = Character.toUpperCase(c1);
1153
char u2 = Character.toUpperCase(c2);
1157
// Unfortunately, conversion to uppercase does not work properly
1158
// for the Georgian alphabet, which has strange rules about case
1159
// conversion. So we need to make one last check before
1161
if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) {
1171
* Returns a hash code for this string. The hash code for a
1172
* <code>String</code> object is computed as
1174
* s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
1175
* </pre></blockquote>
1176
* using <code>int</code> arithmetic, where <code>s[i]</code> is the
1177
* <i>i</i>th character of the string, <code>n</code> is the length of
1178
* the string, and <code>^</code> indicates exponentiation.
1179
* (The hash value of the empty string is zero.)
1181
* @return a hash code value for this object.
1183
static int hashCode(cli.System.String _this) {
1185
// NOTE having the get_Length in the for condition is actually faster than hoisting it,
1186
// the CLR JIT recognizes this pattern and optimizes the array bounds check in get_Chars.
1187
for (int i = 0; i < _this.get_Length(); i++)
1189
h = h * 31 + _this.get_Chars(i);
1195
* Returns the index within this string of the first occurrence of
1196
* the specified character. If a character with value
1197
* <code>ch</code> occurs in the character sequence represented by
1198
* this <code>String</code> object, then the index (in Unicode
1199
* code units) of the first such occurrence is returned. For
1200
* values of <code>ch</code> in the range from 0 to 0xFFFF
1201
* (inclusive), this is the smallest value <i>k</i> such that:
1203
* this.charAt(<i>k</i>) == ch
1204
* </pre></blockquote>
1205
* is true. For other values of <code>ch</code>, it is the
1206
* smallest value <i>k</i> such that:
1208
* this.codePointAt(<i>k</i>) == ch
1209
* </pre></blockquote>
1210
* is true. In either case, if no such character occurs in this
1211
* string, then <code>-1</code> is returned.
1213
* @param ch a character (Unicode code point).
1214
* @return the index of the first occurrence of the character in the
1215
* character sequence represented by this object, or
1216
* <code>-1</code> if the character does not occur.
1218
static int indexOf(cli.System.String _this, int ch) {
1219
return indexOf(_this, ch, 0);
1223
* Returns the index within this string of the first occurrence of the
1224
* specified character, starting the search at the specified index.
1226
* If a character with value <code>ch</code> occurs in the
1227
* character sequence represented by this <code>String</code>
1228
* object at an index no smaller than <code>fromIndex</code>, then
1229
* the index of the first such occurrence is returned. For values
1230
* of <code>ch</code> in the range from 0 to 0xFFFF (inclusive),
1231
* this is the smallest value <i>k</i> such that:
1233
* (this.charAt(<i>k</i>) == ch) && (<i>k</i> >= fromIndex)
1234
* </pre></blockquote>
1235
* is true. For other values of <code>ch</code>, it is the
1236
* smallest value <i>k</i> such that:
1238
* (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> >= fromIndex)
1239
* </pre></blockquote>
1240
* is true. In either case, if no such character occurs in this
1241
* string at or after position <code>fromIndex</code>, then
1242
* <code>-1</code> is returned.
1245
* There is no restriction on the value of <code>fromIndex</code>. If it
1246
* is negative, it has the same effect as if it were zero: this entire
1247
* string may be searched. If it is greater than the length of this
1248
* string, it has the same effect as if it were equal to the length of
1249
* this string: <code>-1</code> is returned.
1251
* <p>All indices are specified in <code>char</code> values
1252
* (Unicode code units).
1254
* @param ch a character (Unicode code point).
1255
* @param fromIndex the index to start the search from.
1256
* @return the index of the first occurrence of the character in the
1257
* character sequence represented by this object that is greater
1258
* than or equal to <code>fromIndex</code>, or <code>-1</code>
1259
* if the character does not occur.
1261
static int indexOf(cli.System.String _this, int ch, int fromIndex) {
1262
int max = _this.get_Length();
1264
if (fromIndex < 0) {
1266
} else if (fromIndex >= max) {
1267
// Note: fromIndex might be near -1>>>1.
1272
if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
1273
// handle most cases here (ch is a BMP code point or a
1274
// negative value (invalid code point))
1275
for (; i < max ; i++) {
1276
if (_this.get_Chars(i) == ch) {
1282
return indexOfSupplementary(_this, ch, fromIndex);
1287
* Handles (rare) calls of indexOf with a supplementary character.
1289
private static int indexOfSupplementary(cli.System.String _this, int ch, int fromIndex) {
1290
if (Character.isValidCodePoint(ch)) {
1291
final char hi = Character.highSurrogate(ch);
1292
final char lo = Character.lowSurrogate(ch);
1293
final int max = _this.get_Length() - 1;
1294
for (int i = fromIndex; i < max; i++) {
1295
if (_this.get_Chars(i) == hi && _this.get_Chars(i+1) == lo) {
1304
* Returns the index within this string of the last occurrence of
1305
* the specified character. For values of <code>ch</code> in the
1306
* range from 0 to 0xFFFF (inclusive), the index (in Unicode code
1307
* units) returned is the largest value <i>k</i> such that:
1309
* this.charAt(<i>k</i>) == ch
1310
* </pre></blockquote>
1311
* is true. For other values of <code>ch</code>, it is the
1312
* largest value <i>k</i> such that:
1314
* this.codePointAt(<i>k</i>) == ch
1315
* </pre></blockquote>
1316
* is true. In either case, if no such character occurs in this
1317
* string, then <code>-1</code> is returned. The
1318
* <code>String</code> is searched backwards starting at the last
1321
* @param ch a character (Unicode code point).
1322
* @return the index of the last occurrence of the character in the
1323
* character sequence represented by this object, or
1324
* <code>-1</code> if the character does not occur.
1326
static int lastIndexOf(cli.System.String _this, int ch) {
1327
return lastIndexOf(_this, ch, _this.get_Length() - 1);
1331
* Returns the index within this string of the last occurrence of
1332
* the specified character, searching backward starting at the
1333
* specified index. For values of <code>ch</code> in the range
1334
* from 0 to 0xFFFF (inclusive), the index returned is the largest
1335
* value <i>k</i> such that:
1337
* (this.charAt(<i>k</i>) == ch) && (<i>k</i> <= fromIndex)
1338
* </pre></blockquote>
1339
* is true. For other values of <code>ch</code>, it is the
1340
* largest value <i>k</i> such that:
1342
* (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> <= fromIndex)
1343
* </pre></blockquote>
1344
* is true. In either case, if no such character occurs in this
1345
* string at or before position <code>fromIndex</code>, then
1346
* <code>-1</code> is returned.
1348
* <p>All indices are specified in <code>char</code> values
1349
* (Unicode code units).
1351
* @param ch a character (Unicode code point).
1352
* @param fromIndex the index to start the search from. There is no
1353
* restriction on the value of <code>fromIndex</code>. If it is
1354
* greater than or equal to the length of this string, it has
1355
* the same effect as if it were equal to one less than the
1356
* length of this string: this entire string may be searched.
1357
* If it is negative, it has the same effect as if it were -1:
1359
* @return the index of the last occurrence of the character in the
1360
* character sequence represented by this object that is less
1361
* than or equal to <code>fromIndex</code>, or <code>-1</code>
1362
* if the character does not occur before that point.
1364
static int lastIndexOf(cli.System.String _this, int ch, int fromIndex) {
1365
if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
1366
// handle most cases here (ch is a BMP code point or a
1367
// negative value (invalid code point))
1368
int i = Math.min(fromIndex, _this.get_Length() - 1);
1369
for (; i >= 0; i--) {
1370
if (_this.get_Chars(i) == ch) {
1376
return lastIndexOfSupplementary(_this, ch, fromIndex);
1381
* Handles (rare) calls of lastIndexOf with a supplementary character.
1383
private static int lastIndexOfSupplementary(cli.System.String _this, int ch, int fromIndex) {
1384
if (Character.isValidCodePoint(ch)) {
1385
char hi = Character.highSurrogate(ch);
1386
char lo = Character.lowSurrogate(ch);
1387
int i = Math.min(fromIndex, _this.get_Length() - 2);
1388
for (; i >= 0; i--) {
1389
if (_this.get_Chars(i) == hi && _this.get_Chars(i+1) == lo) {
1398
* Returns the index within this string of the first occurrence of the
1399
* specified substring.
1401
* <p>The returned index is the smallest value <i>k</i> for which:
1403
* this.startsWith(str, <i>k</i>)
1404
* </pre></blockquote>
1405
* If no such value of <i>k</i> exists, then {@code -1} is returned.
1407
* @param str the substring to search for.
1408
* @return the index of the first occurrence of the specified substring,
1409
* or {@code -1} if there is no such occurrence.
1411
static int indexOf(String _this, String str) {
1412
return indexOf(_this, str, 0);
1416
* Returns the index within this string of the first occurrence of the
1417
* specified substring, starting at the specified index.
1419
* <p>The returned index is the smallest value <i>k</i> for which:
1421
* <i>k</i> >= fromIndex && this.startsWith(str, <i>k</i>)
1422
* </pre></blockquote>
1423
* If no such value of <i>k</i> exists, then {@code -1} is returned.
1425
* @param str the substring to search for.
1426
* @param fromIndex the index from which to start the search.
1427
* @return the index of the first occurrence of the specified substring,
1428
* starting at the specified index,
1429
* or {@code -1} if there is no such occurrence.
1431
static int indexOf(String _this, String str, int fromIndex) {
1432
// start by dereferencing _this, to make sure we throw a NullPointerException if _this is null
1433
int slen = _this.length();
1434
int olen = str.length();
1437
return Math.max(0, Math.min(fromIndex, slen));
1443
char firstChar = str.charAt(0);
1444
// Java allows fromIndex to both below zero or above the length of the string, .NET doesn't
1445
int index = Math.max(0, Math.min(slen, fromIndex));
1446
int end = slen - olen;
1447
while (index >= 0 && index <= end)
1449
if (cli.System.String.CompareOrdinal(_this, index, str, 0, olen) == 0)
1453
index = _this.indexOf(firstChar, index + 1);
1459
* Code shared by String and StringBuffer to do searches. The
1460
* source is the character array being searched, and the target
1461
* is the string being searched for.
1463
* @param source the characters being searched.
1464
* @param sourceOffset offset of the source string.
1465
* @param sourceCount count of the source string.
1466
* @param target the characters being searched for.
1467
* @param targetOffset offset of the target string.
1468
* @param targetCount count of the target string.
1469
* @param fromIndex the index to begin searching from.
1471
static int indexOf(char[] source, int sourceOffset, int sourceCount,
1472
char[] target, int targetOffset, int targetCount,
1474
if (fromIndex >= sourceCount) {
1475
return (targetCount == 0 ? sourceCount : -1);
1477
if (fromIndex < 0) {
1480
if (targetCount == 0) {
1484
char first = target[targetOffset];
1485
int max = sourceOffset + (sourceCount - targetCount);
1487
for (int i = sourceOffset + fromIndex; i <= max; i++) {
1488
/* Look for first character. */
1489
if (source[i] != first) {
1490
while (++i <= max && source[i] != first);
1493
/* Found first character, now look at the rest of v2 */
1496
int end = j + targetCount - 1;
1497
for (int k = targetOffset + 1; j < end && source[j]
1498
== target[k]; j++, k++);
1501
/* Found whole string. */
1502
return i - sourceOffset;
1510
* Returns the index within this string of the last occurrence of the
1511
* specified substring. The last occurrence of the empty string ""
1512
* is considered to occur at the index value {@code this.length()}.
1514
* <p>The returned index is the largest value <i>k</i> for which:
1516
* this.startsWith(str, <i>k</i>)
1517
* </pre></blockquote>
1518
* If no such value of <i>k</i> exists, then {@code -1} is returned.
1520
* @param str the substring to search for.
1521
* @return the index of the last occurrence of the specified substring,
1522
* or {@code -1} if there is no such occurrence.
1524
static int lastIndexOf(String _this, String str) {
1525
return lastIndexOf(_this, str, _this.length());
1529
* Returns the index within this string of the last occurrence of the
1530
* specified substring, searching backward starting at the specified index.
1532
* <p>The returned index is the largest value <i>k</i> for which:
1534
* <i>k</i> <= fromIndex && this.startsWith(str, <i>k</i>)
1535
* </pre></blockquote>
1536
* If no such value of <i>k</i> exists, then {@code -1} is returned.
1538
* @param str the substring to search for.
1539
* @param fromIndex the index to start the search from.
1540
* @return the index of the last occurrence of the specified substring,
1541
* searching backward from the specified index,
1542
* or {@code -1} if there is no such occurrence.
1544
static int lastIndexOf(String _this, String str, int fromIndex) {
1545
// start by dereferencing s, to make sure we throw a NullPointerException if s is null
1546
int slen = _this.length();
1551
int olen = str.length();
1554
return Math.min(slen, fromIndex);
1560
cli.System.String cliStr = (cli.System.String)(Object)_this;
1561
char firstChar = str.charAt(0);
1562
// Java allows fromIndex to both below zero or above the length of the string, .NET doesn't
1563
int index = Math.max(0, Math.min(slen - olen, fromIndex));
1566
if (cli.System.String.CompareOrdinal(_this, index, str, 0, olen) == 0)
1570
index = cliStr.LastIndexOf(firstChar, index - 1);
1572
return cli.System.String.CompareOrdinal(_this, 0, str, 0, olen) == 0 ? 0 : -1;
1576
* Code shared by String and StringBuffer to do searches. The
1577
* source is the character array being searched, and the target
1578
* is the string being searched for.
1580
* @param source the characters being searched.
1581
* @param sourceOffset offset of the source string.
1582
* @param sourceCount count of the source string.
1583
* @param target the characters being searched for.
1584
* @param targetOffset offset of the target string.
1585
* @param targetCount count of the target string.
1586
* @param fromIndex the index to begin searching from.
1588
static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
1589
char[] target, int targetOffset, int targetCount,
1592
* Check arguments; return immediately where possible. For
1593
* consistency, don't check for null str.
1595
int rightIndex = sourceCount - targetCount;
1596
if (fromIndex < 0) {
1599
if (fromIndex > rightIndex) {
1600
fromIndex = rightIndex;
1602
/* Empty string always matches. */
1603
if (targetCount == 0) {
1607
int strLastIndex = targetOffset + targetCount - 1;
1608
char strLastChar = target[strLastIndex];
1609
int min = sourceOffset + targetCount - 1;
1610
int i = min + fromIndex;
1612
startSearchForLastChar:
1614
while (i >= min && source[i] != strLastChar) {
1621
int start = j - (targetCount - 1);
1622
int k = strLastIndex - 1;
1625
if (source[j--] != target[k--]) {
1627
continue startSearchForLastChar;
1630
return start - sourceOffset + 1;
1635
* Returns a new string that is a substring of this string. The
1636
* substring begins at the specified <code>beginIndex</code> and
1637
* extends to the character at index <code>endIndex - 1</code>.
1638
* Thus the length of the substring is <code>endIndex-beginIndex</code>.
1642
* "hamburger".substring(4, 8) returns "urge"
1643
* "smiles".substring(1, 5) returns "mile"
1644
* </pre></blockquote>
1646
* @param beginIndex the beginning index, inclusive.
1647
* @param endIndex the ending index, exclusive.
1648
* @return the specified substring.
1649
* @exception IndexOutOfBoundsException if the
1650
* <code>beginIndex</code> is negative, or
1651
* <code>endIndex</code> is larger than the length of
1652
* this <code>String</code> object, or
1653
* <code>beginIndex</code> is larger than
1654
* <code>endIndex</code>.
1656
static String substring(cli.System.String _this, int beginIndex, int endIndex) {
1657
if (beginIndex < 0) {
1658
throw new StringIndexOutOfBoundsException(beginIndex);
1660
if (endIndex > _this.get_Length()) {
1661
throw new StringIndexOutOfBoundsException(endIndex);
1663
int subLen = endIndex - beginIndex;
1665
throw new StringIndexOutOfBoundsException(subLen);
1667
return ((beginIndex == 0) && (endIndex == _this.get_Length())) ? (String)(Object)_this
1668
: _this.Substring(beginIndex, subLen);
1672
* Concatenates the specified string to the end of this string.
1674
* If the length of the argument string is <code>0</code>, then this
1675
* <code>String</code> object is returned. Otherwise, a new
1676
* <code>String</code> object is created, representing a character
1677
* sequence that is the concatenation of the character sequence
1678
* represented by this <code>String</code> object and the character
1679
* sequence represented by the argument string.<p>
1682
* "cares".concat("s") returns "caress"
1683
* "to".concat("get").concat("her") returns "together"
1684
* </pre></blockquote>
1686
* @param str the <code>String</code> that is concatenated to the end
1687
* of this <code>String</code>.
1688
* @return a string that represents the concatenation of this object's
1689
* characters followed by the string argument's characters.
1691
static String concat(String _this, String str) {
1692
int otherLen = str.length();
1693
if (otherLen == 0) {
1696
return cli.System.String.Concat(_this, str);
1700
* Returns a new string resulting from replacing all occurrences of
1701
* <code>oldChar</code> in this string with <code>newChar</code>.
1703
* If the character <code>oldChar</code> does not occur in the
1704
* character sequence represented by this <code>String</code> object,
1705
* then a reference to this <code>String</code> object is returned.
1706
* Otherwise, a new <code>String</code> object is created that
1707
* represents a character sequence identical to the character sequence
1708
* represented by this <code>String</code> object, except that every
1709
* occurrence of <code>oldChar</code> is replaced by an occurrence
1710
* of <code>newChar</code>.
1714
* "mesquite in your cellar".replace('e', 'o')
1715
* returns "mosquito in your collar"
1716
* "the war of baronets".replace('r', 'y')
1717
* returns "the way of bayonets"
1718
* "sparring with a purple porpoise".replace('p', 't')
1719
* returns "starring with a turtle tortoise"
1720
* "JonL".replace('q', 'x') returns "JonL" (no change)
1721
* </pre></blockquote>
1723
* @param oldChar the old character.
1724
* @param newChar the new character.
1725
* @return a string derived from this string by replacing every
1726
* occurrence of <code>oldChar</code> with <code>newChar</code>.
1728
static String replace(String _this, char oldChar, char newChar) {
1729
if (oldChar != newChar) {
1730
int len = _this.length();
1734
if (_this.charAt(i) == oldChar) {
1739
char buf[] = new char[len];
1740
for (int j = 0 ; j < i ; j++) {
1741
buf[j] = _this.charAt(j);
1744
char c = _this.charAt(i);
1745
buf[i] = (c == oldChar) ? newChar : c;
1748
return new String(buf, true);
1755
* Returns true if and only if this string contains the specified
1756
* sequence of char values.
1758
* @param s the sequence to search for
1759
* @return true if this string contains <code>s</code>, false otherwise
1760
* @throws NullPointerException if <code>s</code> is <code>null</code>
1763
static boolean contains(String _this, CharSequence s) {
1764
return indexOf(_this, s.toString()) > -1;
1768
* Replaces each substring of this string that matches the literal target
1769
* sequence with the specified literal replacement sequence. The
1770
* replacement proceeds from the beginning of the string to the end, for
1771
* example, replacing "aa" with "b" in the string "aaa" will result in
1772
* "ba" rather than "ab".
1774
* @param target The sequence of char values to be replaced
1775
* @param replacement The replacement sequence of char values
1776
* @return The resulting string
1777
* @throws NullPointerException if <code>target</code> or
1778
* <code>replacement</code> is <code>null</code>.
1781
static String replace(String _this, CharSequence target, CharSequence replacement) {
1782
return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
1783
_this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
1787
* Splits this string around matches of the given
1788
* <a href="../util/regex/Pattern.html#sum">regular expression</a>.
1790
* <p> The array returned by this method contains each substring of this
1791
* string that is terminated by another substring that matches the given
1792
* expression or is terminated by the end of the string. The substrings in
1793
* the array are in the order in which they occur in this string. If the
1794
* expression does not match any part of the input then the resulting array
1795
* has just one element, namely this string.
1797
* <p> The <tt>limit</tt> parameter controls the number of times the
1798
* pattern is applied and therefore affects the length of the resulting
1799
* array. If the limit <i>n</i> is greater than zero then the pattern
1800
* will be applied at most <i>n</i> - 1 times, the array's
1801
* length will be no greater than <i>n</i>, and the array's last entry
1802
* will contain all input beyond the last matched delimiter. If <i>n</i>
1803
* is non-positive then the pattern will be applied as many times as
1804
* possible and the array can have any length. If <i>n</i> is zero then
1805
* the pattern will be applied as many times as possible, the array can
1806
* have any length, and trailing empty strings will be discarded.
1808
* <p> The string <tt>"boo:and:foo"</tt>, for example, yields the
1809
* following results with these parameters:
1811
* <blockquote><table cellpadding=1 cellspacing=0 summary="Split example showing regex, limit, and result">
1817
* <tr><td align=center>:</td>
1818
* <td align=center>2</td>
1819
* <td><tt>{ "boo", "and:foo" }</tt></td></tr>
1820
* <tr><td align=center>:</td>
1821
* <td align=center>5</td>
1822
* <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
1823
* <tr><td align=center>:</td>
1824
* <td align=center>-2</td>
1825
* <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
1826
* <tr><td align=center>o</td>
1827
* <td align=center>5</td>
1828
* <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
1829
* <tr><td align=center>o</td>
1830
* <td align=center>-2</td>
1831
* <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
1832
* <tr><td align=center>o</td>
1833
* <td align=center>0</td>
1834
* <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
1835
* </table></blockquote>
1837
* <p> An invocation of this method of the form
1838
* <i>str.</i><tt>split(</tt><i>regex</i><tt>,</tt> <i>n</i><tt>)</tt>
1839
* yields the same result as the expression
1842
* {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
1843
* compile}<tt>(</tt><i>regex</i><tt>)</tt>.{@link
1844
* java.util.regex.Pattern#split(java.lang.CharSequence,int)
1845
* split}<tt>(</tt><i>str</i><tt>,</tt> <i>n</i><tt>)</tt>
1850
* the delimiting regular expression
1853
* the result threshold, as described above
1855
* @return the array of strings computed by splitting this string
1856
* around matches of the given regular expression
1858
* @throws PatternSyntaxException
1859
* if the regular expression's syntax is invalid
1861
* @see java.util.regex.Pattern
1866
static String[] split(String _this, String regex, int limit) {
1867
/* fastpath if the regex is a
1868
(1)one-char String and this character is not one of the
1869
RegEx's meta characters ".$|()[{^?*+\\", or
1870
(2)two-char String and the first char is the backslash and
1871
the second is not the ascii digit or ascii letter.
1874
if (((regex.length() == 1 &&
1875
".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||
1876
(regex.length() == 2 &&
1877
regex.charAt(0) == '\\' &&
1878
(((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&
1879
((ch-'a')|('z'-ch)) < 0 &&
1880
((ch-'A')|('Z'-ch)) < 0)) &&
1881
(ch < Character.MIN_HIGH_SURROGATE ||
1882
ch > Character.MAX_LOW_SURROGATE))
1886
boolean limited = limit > 0;
1887
ArrayList<String> list = new ArrayList<>();
1888
while ((next = _this.indexOf(ch, off)) != -1) {
1889
if (!limited || list.size() < limit - 1) {
1890
list.add(_this.substring(off, next));
1892
} else { // last one
1893
//assert (list.size() == limit - 1);
1894
list.add(_this.substring(off, _this.length()));
1895
off = _this.length();
1899
// If no match was found, return this
1901
return new String[]{_this};
1903
// Add remaining segment
1904
if (!limited || list.size() < limit)
1905
list.add(_this.substring(off, _this.length()));
1908
int resultSize = list.size();
1910
while (resultSize > 0 && list.get(resultSize - 1).length() == 0)
1912
String[] result = new String[resultSize];
1913
return list.subList(0, resultSize).toArray(result);
1915
return Pattern.compile(regex).split(_this, limit);
1919
* Converts all of the characters in this <code>String</code> to lower
1920
* case using the rules of the given <code>Locale</code>. Case mapping is based
1921
* on the Unicode Standard version specified by the {@link java.lang.Character Character}
1922
* class. Since case mappings are not always 1:1 char mappings, the resulting
1923
* <code>String</code> may be a different length than the original <code>String</code>.
1925
* Examples of lowercase mappings are in the following table:
1926
* <table border="1" summary="Lowercase mapping examples showing language code of locale, upper case, lower case, and description">
1928
* <th>Language Code of Locale</th>
1929
* <th>Upper Case</th>
1930
* <th>Lower Case</th>
1931
* <th>Description</th>
1934
* <td>tr (Turkish)</td>
1935
* <td>\u0130</td>
1936
* <td>\u0069</td>
1937
* <td>capital letter I with dot above -> small letter i</td>
1940
* <td>tr (Turkish)</td>
1941
* <td>\u0049</td>
1942
* <td>\u0131</td>
1943
* <td>capital letter I -> small letter dotless i </td>
1947
* <td>French Fries</td>
1948
* <td>french fries</td>
1949
* <td>lowercased all chars in String</td>
1953
* <td><img src="doc-files/capiota.gif" alt="capiota"><img src="doc-files/capchi.gif" alt="capchi">
1954
* <img src="doc-files/captheta.gif" alt="captheta"><img src="doc-files/capupsil.gif" alt="capupsil">
1955
* <img src="doc-files/capsigma.gif" alt="capsigma"></td>
1956
* <td><img src="doc-files/iota.gif" alt="iota"><img src="doc-files/chi.gif" alt="chi">
1957
* <img src="doc-files/theta.gif" alt="theta"><img src="doc-files/upsilon.gif" alt="upsilon">
1958
* <img src="doc-files/sigma1.gif" alt="sigma"></td>
1959
* <td>lowercased all chars in String</td>
1963
* @param locale use the case transformation rules for this locale
1964
* @return the <code>String</code>, converted to lowercase.
1965
* @see java.lang.String#toLowerCase()
1966
* @see java.lang.String#toUpperCase()
1967
* @see java.lang.String#toUpperCase(Locale)
1970
static String toLowerCase(String _this, Locale locale) {
1971
if (locale == null) {
1972
throw new NullPointerException();
1976
final int len = _this.length();
1978
/* Now check if there are any characters that need to be changed. */
1980
for (firstUpper = 0 ; firstUpper < len; ) {
1981
char c = _this.charAt(firstUpper);
1982
if ((c >= Character.MIN_HIGH_SURROGATE)
1983
&& (c <= Character.MAX_HIGH_SURROGATE)) {
1984
int supplChar = _this.codePointAt(firstUpper);
1985
if (supplChar != Character.toLowerCase(supplChar)) {
1988
firstUpper += Character.charCount(supplChar);
1990
if (c != Character.toLowerCase(c)) {
1999
char[] result = new char[len];
2000
int resultOffset = 0; /* result may grow, so i+resultOffset
2001
* is the write location in result */
2003
/* Just copy the first few lowerCase characters. */
2004
_this.getChars(0, firstUpper, result, 0);
2006
String lang = locale.getLanguage();
2007
boolean localeDependent =
2008
(lang == "tr" || lang == "az" || lang == "lt");
2009
char[] lowerCharArray;
2013
for (int i = firstUpper; i < len; i += srcCount) {
2014
srcChar = (int)_this.charAt(i);
2015
if ((char)srcChar >= Character.MIN_HIGH_SURROGATE
2016
&& (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
2017
srcChar = _this.codePointAt(i);
2018
srcCount = Character.charCount(srcChar);
2022
if (localeDependent || srcChar == '\u03A3') { // GREEK CAPITAL LETTER SIGMA
2023
lowerChar = ConditionalSpecialCasing.toLowerCaseEx(_this, i, locale);
2024
} else if (srcChar == '\u0130') { // LATIN CAPITAL LETTER I DOT
2025
lowerChar = Character.ERROR;
2027
lowerChar = Character.toLowerCase(srcChar);
2029
if ((lowerChar == Character.ERROR)
2030
|| (lowerChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
2031
if (lowerChar == Character.ERROR) {
2032
if (!localeDependent && srcChar == '\u0130') {
2034
ConditionalSpecialCasing.toLowerCaseCharArray(_this, i, Locale.ENGLISH);
2037
ConditionalSpecialCasing.toLowerCaseCharArray(_this, i, locale);
2039
} else if (srcCount == 2) {
2040
resultOffset += Character.toChars(lowerChar, result, i + resultOffset) - srcCount;
2043
lowerCharArray = Character.toChars(lowerChar);
2046
/* Grow result if needed */
2047
int mapLen = lowerCharArray.length;
2048
if (mapLen > srcCount) {
2049
char[] result2 = new char[result.length + mapLen - srcCount];
2050
System.arraycopy(result, 0, result2, 0, i + resultOffset);
2053
for (int x = 0; x < mapLen; ++x) {
2054
result[i + resultOffset + x] = lowerCharArray[x];
2056
resultOffset += (mapLen - srcCount);
2058
result[i + resultOffset] = (char)lowerChar;
2061
return new String(result, 0, len + resultOffset);
2065
* Converts all of the characters in this <code>String</code> to lower
2066
* case using the rules of the default locale. This is equivalent to calling
2067
* <code>toLowerCase(Locale.getDefault())</code>.
2069
* <b>Note:</b> This method is locale sensitive, and may produce unexpected
2070
* results if used for strings that are intended to be interpreted locale
2072
* Examples are programming language identifiers, protocol keys, and HTML
2074
* For instance, <code>"TITLE".toLowerCase()</code> in a Turkish locale
2075
* returns <code>"t\u005Cu0131tle"</code>, where '\u005Cu0131' is the
2076
* LATIN SMALL LETTER DOTLESS I character.
2077
* To obtain correct results for locale insensitive strings, use
2078
* <code>toLowerCase(Locale.ENGLISH)</code>.
2080
* @return the <code>String</code>, converted to lowercase.
2081
* @see java.lang.String#toLowerCase(Locale)
2083
static String toLowerCase(String _this) {
2084
return toLowerCase(_this, Locale.getDefault());
2088
* Converts all of the characters in this <code>String</code> to upper
2089
* case using the rules of the given <code>Locale</code>. Case mapping is based
2090
* on the Unicode Standard version specified by the {@link java.lang.Character Character}
2091
* class. Since case mappings are not always 1:1 char mappings, the resulting
2092
* <code>String</code> may be a different length than the original <code>String</code>.
2094
* Examples of locale-sensitive and 1:M case mappings are in the following table.
2096
* <table border="1" summary="Examples of locale-sensitive and 1:M case mappings. Shows Language code of locale, lower case, upper case, and description.">
2098
* <th>Language Code of Locale</th>
2099
* <th>Lower Case</th>
2100
* <th>Upper Case</th>
2101
* <th>Description</th>
2104
* <td>tr (Turkish)</td>
2105
* <td>\u0069</td>
2106
* <td>\u0130</td>
2107
* <td>small letter i -> capital letter I with dot above</td>
2110
* <td>tr (Turkish)</td>
2111
* <td>\u0131</td>
2112
* <td>\u0049</td>
2113
* <td>small letter dotless i -> capital letter I</td>
2117
* <td>\u00df</td>
2118
* <td>\u0053 \u0053</td>
2119
* <td>small letter sharp s -> two letters: SS</td>
2123
* <td>Fahrvergnügen</td>
2124
* <td>FAHRVERGNÜGEN</td>
2128
* @param locale use the case transformation rules for this locale
2129
* @return the <code>String</code>, converted to uppercase.
2130
* @see java.lang.String#toUpperCase()
2131
* @see java.lang.String#toLowerCase()
2132
* @see java.lang.String#toLowerCase(Locale)
2135
static String toUpperCase(String _this, Locale locale) {
2136
if (locale == null) {
2137
throw new NullPointerException();
2141
final int len = _this.length();
2143
/* Now check if there are any characters that need to be changed. */
2145
for (firstLower = 0 ; firstLower < len; ) {
2146
int c = (int)_this.charAt(firstLower);
2148
if ((c >= Character.MIN_HIGH_SURROGATE)
2149
&& (c <= Character.MAX_HIGH_SURROGATE)) {
2150
c = _this.codePointAt(firstLower);
2151
srcCount = Character.charCount(c);
2155
int upperCaseChar = Character.toUpperCaseEx(c);
2156
if ((upperCaseChar == Character.ERROR)
2157
|| (c != upperCaseChar)) {
2160
firstLower += srcCount;
2165
char[] result = new char[len]; /* may grow */
2166
int resultOffset = 0; /* result may grow, so i+resultOffset
2167
* is the write location in result */
2169
/* Just copy the first few upperCase characters. */
2170
_this.getChars(0, firstLower, result, 0);
2172
String lang = locale.getLanguage();
2173
boolean localeDependent =
2174
(lang == "tr" || lang == "az" || lang == "lt");
2175
char[] upperCharArray;
2179
for (int i = firstLower; i < len; i += srcCount) {
2180
srcChar = (int)_this.charAt(i);
2181
if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
2182
(char)srcChar <= Character.MAX_HIGH_SURROGATE) {
2183
srcChar = _this.codePointAt(i);
2184
srcCount = Character.charCount(srcChar);
2188
if (localeDependent) {
2189
upperChar = ConditionalSpecialCasing.toUpperCaseEx(_this, i, locale);
2191
upperChar = Character.toUpperCaseEx(srcChar);
2193
if ((upperChar == Character.ERROR)
2194
|| (upperChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
2195
if (upperChar == Character.ERROR) {
2196
if (localeDependent) {
2198
ConditionalSpecialCasing.toUpperCaseCharArray(_this, i, locale);
2200
upperCharArray = Character.toUpperCaseCharArray(srcChar);
2202
} else if (srcCount == 2) {
2203
resultOffset += Character.toChars(upperChar, result, i + resultOffset) - srcCount;
2206
upperCharArray = Character.toChars(upperChar);
2209
/* Grow result if needed */
2210
int mapLen = upperCharArray.length;
2211
if (mapLen > srcCount) {
2212
char[] result2 = new char[result.length + mapLen - srcCount];
2213
System.arraycopy(result, 0, result2, 0, i + resultOffset);
2216
for (int x = 0; x < mapLen; ++x) {
2217
result[i + resultOffset + x] = upperCharArray[x];
2219
resultOffset += (mapLen - srcCount);
2221
result[i + resultOffset] = (char)upperChar;
2224
return new String(result, 0, len + resultOffset);
2228
* Converts all of the characters in this <code>String</code> to upper
2229
* case using the rules of the default locale. This method is equivalent to
2230
* <code>toUpperCase(Locale.getDefault())</code>.
2232
* <b>Note:</b> This method is locale sensitive, and may produce unexpected
2233
* results if used for strings that are intended to be interpreted locale
2235
* Examples are programming language identifiers, protocol keys, and HTML
2237
* For instance, <code>"title".toUpperCase()</code> in a Turkish locale
2238
* returns <code>"T\u005Cu0130TLE"</code>, where '\u005Cu0130' is the
2239
* LATIN CAPITAL LETTER I WITH DOT ABOVE character.
2240
* To obtain correct results for locale insensitive strings, use
2241
* <code>toUpperCase(Locale.ENGLISH)</code>.
2243
* @return the <code>String</code>, converted to uppercase.
2244
* @see java.lang.String#toUpperCase(Locale)
2246
static String toUpperCase(String _this) {
2247
return toUpperCase(_this, Locale.getDefault());
2251
* Returns a copy of the string, with leading and trailing whitespace
2254
* If this <code>String</code> object represents an empty character
2255
* sequence, or the first and last characters of character sequence
2256
* represented by this <code>String</code> object both have codes
2257
* greater than <code>'\u0020'</code> (the space character), then a
2258
* reference to this <code>String</code> object is returned.
2260
* Otherwise, if there is no character with a code greater than
2261
* <code>'\u0020'</code> in the string, then a new
2262
* <code>String</code> object representing an empty string is created
2265
* Otherwise, let <i>k</i> be the index of the first character in the
2266
* string whose code is greater than <code>'\u0020'</code>, and let
2267
* <i>m</i> be the index of the last character in the string whose code
2268
* is greater than <code>'\u0020'</code>. A new <code>String</code>
2269
* object is created, representing the substring of this string that
2270
* begins with the character at index <i>k</i> and ends with the
2271
* character at index <i>m</i>-that is, the result of
2272
* <code>this.substring(<i>k</i>, <i>m</i>+1)</code>.
2274
* This method may be used to trim whitespace (as defined above) from
2275
* the beginning and end of a string.
2277
* @return A copy of this string with leading and trailing white
2278
* space removed, or this string if it has no leading or
2279
* trailing white space.
2281
static String trim(String _this) {
2282
int len = _this.length();
2285
while ((st < len) && (_this.charAt(st) <= ' ')) {
2288
while ((st < len) && (_this.charAt(len - 1) <= ' ')) {
2291
return ((st > 0) || (len < _this.length())) ? _this.substring(st, len) : _this;
2295
* Returns a formatted string using the specified format string and
2298
* <p> The locale always used is the one returned by {@link
2299
* java.util.Locale#getDefault() Locale.getDefault()}.
2302
* A <a href="../util/Formatter.html#syntax">format string</a>
2305
* Arguments referenced by the format specifiers in the format
2306
* string. If there are more arguments than format specifiers, the
2307
* extra arguments are ignored. The number of arguments is
2308
* variable and may be zero. The maximum number of arguments is
2309
* limited by the maximum dimension of a Java array as defined by
2310
* <cite>The Java™ Virtual Machine Specification</cite>.
2311
* The behaviour on a
2312
* <tt>null</tt> argument depends on the <a
2313
* href="../util/Formatter.html#syntax">conversion</a>.
2315
* @throws IllegalFormatException
2316
* If a format string contains an illegal syntax, a format
2317
* specifier that is incompatible with the given arguments,
2318
* insufficient arguments given the format string, or other
2319
* illegal conditions. For specification of all possible
2320
* formatting errors, see the <a
2321
* href="../util/Formatter.html#detail">Details</a> section of the
2322
* formatter class specification.
2324
* @throws NullPointerException
2325
* If the <tt>format</tt> is <tt>null</tt>
2327
* @return A formatted string
2329
* @see java.util.Formatter
2332
public static String format(String format, Object... args) {
2333
return new Formatter().format(format, args).toString();
2337
* Returns a formatted string using the specified locale, format string,
2341
* The {@linkplain java.util.Locale locale} to apply during
2342
* formatting. If <tt>l</tt> is <tt>null</tt> then no localization
2346
* A <a href="../util/Formatter.html#syntax">format string</a>
2349
* Arguments referenced by the format specifiers in the format
2350
* string. If there are more arguments than format specifiers, the
2351
* extra arguments are ignored. The number of arguments is
2352
* variable and may be zero. The maximum number of arguments is
2353
* limited by the maximum dimension of a Java array as defined by
2354
* <cite>The Java™ Virtual Machine Specification</cite>.
2355
* The behaviour on a
2356
* <tt>null</tt> argument depends on the <a
2357
* href="../util/Formatter.html#syntax">conversion</a>.
2359
* @throws IllegalFormatException
2360
* If a format string contains an illegal syntax, a format
2361
* specifier that is incompatible with the given arguments,
2362
* insufficient arguments given the format string, or other
2363
* illegal conditions. For specification of all possible
2364
* formatting errors, see the <a
2365
* href="../util/Formatter.html#detail">Details</a> section of the
2366
* formatter class specification
2368
* @throws NullPointerException
2369
* If the <tt>format</tt> is <tt>null</tt>
2371
* @return A formatted string
2373
* @see java.util.Formatter
2376
public static String format(Locale l, String format, Object... args) {
2377
return new Formatter(l).format(format, args).toString();
2381
* Returns the string representation of the <code>Object</code> argument.
2383
* @param obj an <code>Object</code>.
2384
* @return if the argument is <code>null</code>, then a string equal to
2385
* <code>"null"</code>; otherwise, the value of
2386
* <code>obj.toString()</code> is returned.
2387
* @see java.lang.Object#toString()
2389
public static String valueOf(Object obj) {
2390
return (obj == null) ? "null" : obj.toString();
2394
* Returns the string representation of the <code>char</code> array
2395
* argument. The contents of the character array are copied; subsequent
2396
* modification of the character array does not affect the newly
2399
* @param data a <code>char</code> array.
2400
* @return a newly allocated string representing the same sequence of
2401
* characters contained in the character array argument.
2403
public static String valueOf(char data[]) {
2404
return new String(data);
2408
* Returns the string representation of a specific subarray of the
2409
* <code>char</code> array argument.
2411
* The <code>offset</code> argument is the index of the first
2412
* character of the subarray. The <code>count</code> argument
2413
* specifies the length of the subarray. The contents of the subarray
2414
* are copied; subsequent modification of the character array does not
2415
* affect the newly created string.
2417
* @param data the character array.
2418
* @param offset the initial offset into the value of the
2419
* <code>String</code>.
2420
* @param count the length of the value of the <code>String</code>.
2421
* @return a string representing the sequence of characters contained
2422
* in the subarray of the character array argument.
2423
* @exception IndexOutOfBoundsException if <code>offset</code> is
2424
* negative, or <code>count</code> is negative, or
2425
* <code>offset+count</code> is larger than
2426
* <code>data.length</code>.
2428
public static String valueOf(char data[], int offset, int count) {
2429
return new String(data, offset, count);
2433
* Returns a String that represents the character sequence in the
2436
* @param data the character array.
2437
* @param offset initial offset of the subarray.
2438
* @param count length of the subarray.
2439
* @return a <code>String</code> that contains the characters of the
2440
* specified subarray of the character array.
2442
public static String copyValueOf(char data[], int offset, int count) {
2443
// All public String constructors now copy the data.
2444
return new String(data, offset, count);
2448
* Returns a String that represents the character sequence in the
2451
* @param data the character array.
2452
* @return a <code>String</code> that contains the characters of the
2455
public static String copyValueOf(char data[]) {
2456
return new String(data);
2460
* Returns the string representation of the <code>boolean</code> argument.
2462
* @param b a <code>boolean</code>.
2463
* @return if the argument is <code>true</code>, a string equal to
2464
* <code>"true"</code> is returned; otherwise, a string equal to
2465
* <code>"false"</code> is returned.
2467
public static String valueOf(boolean b) {
2468
return b ? "true" : "false";
2472
* Returns the string representation of the <code>int</code> argument.
2474
* The representation is exactly the one returned by the
2475
* <code>Integer.toString</code> method of one argument.
2477
* @param i an <code>int</code>.
2478
* @return a string representation of the <code>int</code> argument.
2479
* @see java.lang.Integer#toString(int, int)
2481
public static String valueOf(int i) {
2482
return Integer.toString(i);
2486
* Returns the string representation of the <code>long</code> argument.
2488
* The representation is exactly the one returned by the
2489
* <code>Long.toString</code> method of one argument.
2491
* @param l a <code>long</code>.
2492
* @return a string representation of the <code>long</code> argument.
2493
* @see java.lang.Long#toString(long)
2495
public static String valueOf(long l) {
2496
return Long.toString(l);
2500
* Returns the string representation of the <code>float</code> argument.
2502
* The representation is exactly the one returned by the
2503
* <code>Float.toString</code> method of one argument.
2505
* @param f a <code>float</code>.
2506
* @return a string representation of the <code>float</code> argument.
2507
* @see java.lang.Float#toString(float)
2509
public static String valueOf(float f) {
2510
return Float.toString(f);
2514
* Returns the string representation of the <code>double</code> argument.
2516
* The representation is exactly the one returned by the
2517
* <code>Double.toString</code> method of one argument.
2519
* @param d a <code>double</code>.
2520
* @return a string representation of the <code>double</code> argument.
2521
* @see java.lang.Double#toString(double)
2523
public static String valueOf(double d) {
2524
return Double.toString(d);
2528
* Seed value used for each alternative hash calculated.
2530
private static final int HASHING_SEED;
2533
long nanos = System.nanoTime();
2534
long now = System.currentTimeMillis();
2535
int SEED_MATERIAL[] = {
2536
System.identityHashCode(String.class),
2537
System.identityHashCode(System.class),
2538
(int) (nanos >>> 32),
2542
(int) (System.nanoTime() >>> 2)
2545
// Use murmur3 to scramble the seeding material.
2546
// Inline implementation to avoid loading classes
2550
for (int k1 : SEED_MATERIAL) {
2552
k1 = (k1 << 15) | (k1 >>> 17);
2556
h1 = (h1 << 13) | (h1 >>> 19);
2557
h1 = h1 * 5 + 0xe6546b64;
2560
// tail (always empty, as body is always 32-bit chunks)
2564
h1 ^= SEED_MATERIAL.length * 4;
2566
// finalization mix force all bits of a hash block to avalanche
2577
* Calculates a 32-bit hash value for this string.
2579
* @return a 32-bit hash value for this string.
2581
static int hash32(String _this) {
2582
// [IKVM] We don't bother with murmur32 and just use the .NET hash code
2583
// and hope that it is good enough. We xor with HASHING_SEED to avoid
2584
// returning predictable values (this does not help against DoS attacks,
2585
// but it will surface constant hash code dependencies).
2586
// If truly randomized string hashes are required (to protect against
2587
// DoS) the .NET 4.5 <UseRandomizedStringHashAlgorithm enabled="1" />
2588
// app.config setting can be used.
2589
return HASHING_SEED ^ ((cli.System.String)(Object)_this).GetHashCode();