1 /* 2 * Hunt - A refined core library for D programming language. 3 * 4 * Copyright (C) 2018-2019 HuntLabs 5 * 6 * Website: https://www.huntlabs.net/ 7 * 8 * Licensed under the Apache-2.0 License. 9 * 10 */ 11 12 module hunt.String; 13 14 import hunt.Nullable; 15 import std.string; 16 17 import std.stdio; 18 void testxxx() { 19 version ( unittest ) { 20 21 writeln("test - unittestd"); 22 } else { 23 24 writeln("test-non-unittest"); 25 } 26 } 27 28 /** 29 * The {@code String} class represents character strings. All 30 * string literals in Java programs, such as {@code "abc"}, are 31 * implemented as instances of this class. 32 * <p> 33 * Strings are constant; their values cannot be changed after they 34 * are created. String buffers support mutable strings. 35 * Because String objects are immutable they can be shared. For example: 36 * <blockquote><pre> 37 * String str = "abc"; 38 * </pre></blockquote><p> 39 * is equivalent to: 40 * <blockquote><pre> 41 * char data[] = {'a', 'b', 'c'}; 42 * String str = new String(data); 43 * </pre></blockquote><p> 44 * Here are some more examples of how strings can be used: 45 * <blockquote><pre> 46 * System.out.println("abc"); 47 * String cde = "cde"; 48 * System.out.println("abc" + cde); 49 * String c = "abc".substring(2,3); 50 * String d = cde.substring(1, 2); 51 * </pre></blockquote> 52 * <p> 53 * The class {@code String} includes methods for examining 54 * individual characters of the sequence, for comparing strings, for 55 * searching strings, for extracting substrings, and for creating a 56 * copy of a string with all characters translated to uppercase or to 57 * lowercase. Case mapping is based on the Unicode Standard version 58 * specified by the {@link java.lang.Character Character} class. 59 * <p> 60 * The Java language provides special support for the string 61 * concatenation operator ( + ), and for conversion of 62 * other objects to strings. For additional information on string 63 * concatenation and conversion, see <i>The Java™ Language Specification</i>. 64 * 65 * <p> Unless otherwise noted, passing a {@code null} argument to a constructor 66 * or method in this class will cause a {@link NullPointerException} to be 67 * thrown. 68 * 69 * <p>A {@code String} represents a string in the UTF-16 format 70 * in which <em>supplementary characters</em> are represented by <em>surrogate 71 * pairs</em> (see the section <a href="Character.html#unicode">Unicode 72 * Character Representations</a> in the {@code Character} class for 73 * more information). 74 * Index values refer to {@code char} code units, so a supplementary 75 * character uses two positions in a {@code String}. 76 * <p>The {@code String} class provides methods for dealing with 77 * Unicode code points (i.e., characters), in addition to those for 78 * dealing with Unicode code units (i.e., {@code char} values). 79 * 80 * <p>Unless otherwise noted, methods for comparing Strings do not take locale 81 * into account. The {@link java.text.Collator} class provides methods for 82 * finer-grain, locale-sensitive String comparison. 83 * 84 * @implNote The implementation of the string concatenation operator is left to 85 * the discretion of a Java compiler, as long as the compiler ultimately conforms 86 * to <i>The Java™ Language Specification</i>. For example, the {@code javac} compiler 87 * may implement the operator with {@code StringBuffer}, {@code StringBuilder}, 88 * or {@code java.lang.invoke.StringConcatFactory} depending on the JDK version. The 89 * implementation of string conversion is typically through the method {@code toString}, 90 * defined by {@code Object} and inherited by all classes in Java. 91 * 92 * @author Lee Boynton 93 * @author Arthur van Hoff 94 * @author Martin Buchholz 95 * @author Ulf Zibis 96 * @see java.lang.Object#toString() 97 * @see java.lang.StringBuffer 98 * @see java.lang.StringBuilder 99 * @see java.nio.charset.Charset 100 * @jls 15.18.1 String Concatenation Operator + 101 */ 102 103 final class String : Nullable!string { 104 105 this() { 106 super(null); 107 } 108 109 this(string value) { 110 super(value); 111 } 112 113 /++ 114 /** 115 * The value is used for character storage. 116 * 117 * @implNote This field is trusted by the VM, and is a subject to 118 * constant folding if String instance is constant. Overwriting this 119 * field after construction will cause problems. 120 * 121 * Additionally, it is marked with {@link Stable} to trust the contents 122 * of the array. No other facility in JDK provides this functionality (yet). 123 * {@link Stable} is safe here, because value is never null. 124 */ 125 @Stable 126 private final byte[] value; 127 128 /** 129 * The identifier of the encoding used to encode the bytes in 130 * {@code value}. The supported values in this implementation are 131 * 132 * LATIN1 133 * UTF16 134 * 135 * @implNote This field is trusted by the VM, and is a subject to 136 * constant folding if String instance is constant. Overwriting this 137 * field after construction will cause problems. 138 */ 139 private final byte coder; 140 141 /** Cache the hash code for the string */ 142 private int hash; // Default to 0 143 144 /** use serialVersionUID from JDK 1.0.2 for interoperability */ 145 private static final long serialVersionUID = -6849794470754667710L; 146 147 /** 148 * If String compaction is disabled, the bytes in {@code value} are 149 * always encoded in UTF16. 150 * 151 * For methods with several possible implementation paths, when String 152 * compaction is disabled, only one code path is taken. 153 * 154 * The instance field value is generally opaque to optimizing JIT 155 * compilers. Therefore, in performance-sensitive place, an explicit 156 * check of the static boolean {@code COMPACT_STRINGS} is done first 157 * before checking the {@code coder} field since the static boolean 158 * {@code COMPACT_STRINGS} would be constant folded away by an 159 * optimizing JIT compiler. The idioms for these cases are as follows. 160 * 161 * For code such as: 162 * 163 * if (coder == LATIN1) { ... } 164 * 165 * can be written more optimally as 166 * 167 * if (coder() == LATIN1) { ... } 168 * 169 * or: 170 * 171 * if (COMPACT_STRINGS && coder == LATIN1) { ... } 172 * 173 * An optimizing JIT compiler can fold the above conditional as: 174 * 175 * COMPACT_STRINGS == true => if (coder == LATIN1) { ... } 176 * COMPACT_STRINGS == false => if (false) { ... } 177 * 178 * @implNote 179 * The actual value for this field is injected by JVM. The static 180 * initialization block is used to set the value here to communicate 181 * that this static final field is not statically foldable, and to 182 * avoid any possible circular dependency during vm initialization. 183 */ 184 static final boolean COMPACT_STRINGS; 185 186 static { 187 COMPACT_STRINGS = true; 188 } 189 190 /** 191 * Class String is special cased within the Serialization Stream Protocol. 192 * 193 * A String instance is written into an ObjectOutputStream according to 194 * <a href="{@docRoot}/../specs/serialization/protocol.html#stream-elements"> 195 * Object Serialization Specification, Section 6.2, "Stream Elements"</a> 196 */ 197 private static final ObjectStreamField[] serialPersistentFields = 198 new ObjectStreamField[0]; 199 200 /** 201 * Initializes a newly created {@code String} object so that it represents 202 * an empty character sequence. Note that use of this constructor is 203 * unnecessary since Strings are immutable. 204 */ 205 String() { 206 this.value = "".value; 207 this.coder = "".coder; 208 } 209 210 /** 211 * Initializes a newly created {@code String} object so that it represents 212 * the same sequence of characters as the argument; in other words, the 213 * newly created string is a copy of the argument string. Unless an 214 * explicit copy of {@code original} is needed, use of this constructor is 215 * unnecessary since Strings are immutable. 216 * 217 * @param original 218 * A {@code String} 219 */ 220 @HotSpotIntrinsicCandidate 221 String(String original) { 222 this.value = original.value; 223 this.coder = original.coder; 224 this.hash = original.hash; 225 } 226 227 /** 228 * Allocates a new {@code String} so that it represents the sequence of 229 * characters currently contained in the character array argument. The 230 * contents of the character array are copied; subsequent modification of 231 * the character array does not affect the newly created string. 232 * 233 * @param value 234 * The initial value of the string 235 */ 236 String(char value[]) { 237 this(value, 0, value.length, null); 238 } 239 240 /** 241 * Allocates a new {@code String} that contains characters from a subarray 242 * of the character array argument. The {@code offset} argument is the 243 * index of the first character of the subarray and the {@code count} 244 * argument specifies the length of the subarray. The contents of the 245 * subarray are copied; subsequent modification of the character array does 246 * not affect the newly created string. 247 * 248 * @param value 249 * Array that is the source of characters 250 * 251 * @param offset 252 * The initial offset 253 * 254 * @param count 255 * The length 256 * 257 * @throws IndexOutOfBoundsException 258 * If {@code offset} is negative, {@code count} is negative, or 259 * {@code offset} is greater than {@code value.length - count} 260 */ 261 String(char value[], int offset, int count) { 262 this(value, offset, count, rangeCheck(value, offset, count)); 263 } 264 265 private static Void rangeCheck(char[] value, int offset, int count) { 266 checkBoundsOffCount(offset, count, value.length); 267 return null; 268 } 269 270 /** 271 * Allocates a new {@code String} that contains characters from a subarray 272 * of the <a href="Character.html#unicode">Unicode code point</a> array 273 * argument. The {@code offset} argument is the index of the first code 274 * point of the subarray and the {@code count} argument specifies the 275 * length of the subarray. The contents of the subarray are converted to 276 * {@code char}s; subsequent modification of the {@code int} array does not 277 * affect the newly created string. 278 * 279 * @param codePoints 280 * Array that is the source of Unicode code points 281 * 282 * @param offset 283 * The initial offset 284 * 285 * @param count 286 * The length 287 * 288 * @throws IllegalArgumentException 289 * If any invalid Unicode code point is found in {@code 290 * codePoints} 291 * 292 * @throws IndexOutOfBoundsException 293 * If {@code offset} is negative, {@code count} is negative, or 294 * {@code offset} is greater than {@code codePoints.length - count} 295 * 296 */ 297 String(int[] codePoints, int offset, int count) { 298 checkBoundsOffCount(offset, count, codePoints.length); 299 if (count == 0) { 300 this.value = "".value; 301 this.coder = "".coder; 302 return; 303 } 304 if (COMPACT_STRINGS) { 305 byte[] val = StringLatin1.toBytes(codePoints, offset, count); 306 if (val != null) { 307 this.coder = LATIN1; 308 this.value = val; 309 return; 310 } 311 } 312 this.coder = UTF16; 313 this.value = StringUTF16.toBytes(codePoints, offset, count); 314 } 315 316 /** 317 * Allocates a new {@code String} constructed from a subarray of an array 318 * of 8-bit integer values. 319 * 320 * <p> The {@code offset} argument is the index of the first byte of the 321 * subarray, and the {@code count} argument specifies the length of the 322 * subarray. 323 * 324 * <p> Each {@code byte} in the subarray is converted to a {@code char} as 325 * specified in the {@link #String(byte[],int) String(byte[],int)} constructor. 326 * 327 * @deprecated This method does not properly convert bytes into characters. 328 * As of JDK 1.1, the preferred way to do this is via the 329 * {@code String} constructors that take a {@link 330 * java.nio.charset.Charset}, charset name, or that use the platform's 331 * default charset. 332 * 333 * @param ascii 334 * The bytes to be converted to characters 335 * 336 * @param hibyte 337 * The top 8 bits of each 16-bit Unicode code unit 338 * 339 * @param offset 340 * The initial offset 341 * @param count 342 * The length 343 * 344 * @throws IndexOutOfBoundsException 345 * If {@code offset} is negative, {@code count} is negative, or 346 * {@code offset} is greater than {@code ascii.length - count} 347 * 348 * @see #String(byte[], int) 349 * @see #String(byte[], int, int, java.lang.String) 350 * @see #String(byte[], int, int, java.nio.charset.Charset) 351 * @see #String(byte[], int, int) 352 * @see #String(byte[], java.lang.String) 353 * @see #String(byte[], java.nio.charset.Charset) 354 * @see #String(byte[]) 355 */ 356 @Deprecated(since="1.1") 357 String(byte ascii[], int hibyte, int offset, int count) { 358 checkBoundsOffCount(offset, count, ascii.length); 359 if (count == 0) { 360 this.value = "".value; 361 this.coder = "".coder; 362 return; 363 } 364 if (COMPACT_STRINGS && (byte)hibyte == 0) { 365 this.value = Arrays.copyOfRange(ascii, offset, offset + count); 366 this.coder = LATIN1; 367 } else { 368 hibyte <<= 8; 369 byte[] val = StringUTF16.newBytesFor(count); 370 for (int i = 0; i < count; i++) { 371 StringUTF16.putChar(val, i, hibyte | (ascii[offset++] & 0xff)); 372 } 373 this.value = val; 374 this.coder = UTF16; 375 } 376 } 377 378 /** 379 * Allocates a new {@code String} containing characters constructed from 380 * an array of 8-bit integer values. Each character <i>c</i> in the 381 * resulting string is constructed from the corresponding component 382 * <i>b</i> in the byte array such that: 383 * 384 * <blockquote><pre> 385 * <b><i>c</i></b> == (char)(((hibyte & 0xff) << 8) 386 * | (<b><i>b</i></b> & 0xff)) 387 * </pre></blockquote> 388 * 389 * @deprecated This method does not properly convert bytes into 390 * characters. As of JDK 1.1, the preferred way to do this is via the 391 * {@code String} constructors that take a {@link 392 * java.nio.charset.Charset}, charset name, or that use the platform's 393 * default charset. 394 * 395 * @param ascii 396 * The bytes to be converted to characters 397 * 398 * @param hibyte 399 * The top 8 bits of each 16-bit Unicode code unit 400 * 401 * @see #String(byte[], int, int, java.lang.String) 402 * @see #String(byte[], int, int, java.nio.charset.Charset) 403 * @see #String(byte[], int, int) 404 * @see #String(byte[], java.lang.String) 405 * @see #String(byte[], java.nio.charset.Charset) 406 * @see #String(byte[]) 407 */ 408 @Deprecated(since="1.1") 409 String(byte ascii[], int hibyte) { 410 this(ascii, hibyte, 0, ascii.length); 411 } 412 413 /** 414 * Constructs a new {@code String} by decoding the specified subarray of 415 * bytes using the specified charset. The length of the new {@code String} 416 * is a function of the charset, and hence may not be equal to the length 417 * of the subarray. 418 * 419 * <p> The behavior of this constructor when the given bytes are not valid 420 * in the given charset is unspecified. The {@link 421 * java.nio.charset.CharsetDecoder} class should be used when more control 422 * over the decoding process is required. 423 * 424 * @param bytes 425 * The bytes to be decoded into characters 426 * 427 * @param offset 428 * The index of the first byte to decode 429 * 430 * @param length 431 * The number of bytes to decode 432 433 * @param charsetName 434 * The name of a supported {@linkplain java.nio.charset.Charset 435 * charset} 436 * 437 * @throws UnsupportedEncodingException 438 * If the named charset is not supported 439 * 440 * @throws IndexOutOfBoundsException 441 * If {@code offset} is negative, {@code length} is negative, or 442 * {@code offset} is greater than {@code bytes.length - length} 443 * 444 */ 445 String(byte bytes[], int offset, int length, String charsetName) 446 throws UnsupportedEncodingException { 447 if (charsetName == null) 448 throw new NullPointerException("charsetName"); 449 checkBoundsOffCount(offset, length, bytes.length); 450 StringCoding.Result ret = 451 StringCoding.decode(charsetName, bytes, offset, length); 452 this.value = ret.value; 453 this.coder = ret.coder; 454 } 455 456 /** 457 * Constructs a new {@code String} by decoding the specified subarray of 458 * bytes using the specified {@linkplain java.nio.charset.Charset charset}. 459 * The length of the new {@code String} is a function of the charset, and 460 * hence may not be equal to the length of the subarray. 461 * 462 * <p> This method always replaces malformed-input and unmappable-character 463 * sequences with this charset's default replacement string. The {@link 464 * java.nio.charset.CharsetDecoder} class should be used when more control 465 * over the decoding process is required. 466 * 467 * @param bytes 468 * The bytes to be decoded into characters 469 * 470 * @param offset 471 * The index of the first byte to decode 472 * 473 * @param length 474 * The number of bytes to decode 475 * 476 * @param charset 477 * The {@linkplain java.nio.charset.Charset charset} to be used to 478 * decode the {@code bytes} 479 * 480 * @throws IndexOutOfBoundsException 481 * If {@code offset} is negative, {@code length} is negative, or 482 * {@code offset} is greater than {@code bytes.length - length} 483 * 484 */ 485 String(byte bytes[], int offset, int length, Charset charset) { 486 if (charset == null) 487 throw new NullPointerException("charset"); 488 checkBoundsOffCount(offset, length, bytes.length); 489 StringCoding.Result ret = 490 StringCoding.decode(charset, bytes, offset, length); 491 this.value = ret.value; 492 this.coder = ret.coder; 493 } 494 495 /** 496 * Constructs a new {@code String} by decoding the specified array of bytes 497 * using the specified {@linkplain java.nio.charset.Charset charset}. The 498 * length of the new {@code String} is a function of the charset, and hence 499 * may not be equal to the length of the byte array. 500 * 501 * <p> The behavior of this constructor when the given bytes are not valid 502 * in the given charset is unspecified. The {@link 503 * java.nio.charset.CharsetDecoder} class should be used when more control 504 * over the decoding process is required. 505 * 506 * @param bytes 507 * The bytes to be decoded into characters 508 * 509 * @param charsetName 510 * The name of a supported {@linkplain java.nio.charset.Charset 511 * charset} 512 * 513 * @throws UnsupportedEncodingException 514 * If the named charset is not supported 515 * 516 */ 517 String(byte bytes[], String charsetName) 518 throws UnsupportedEncodingException { 519 this(bytes, 0, bytes.length, charsetName); 520 } 521 522 /** 523 * Constructs a new {@code String} by decoding the specified array of 524 * bytes using the specified {@linkplain java.nio.charset.Charset charset}. 525 * The length of the new {@code String} is a function of the charset, and 526 * hence may not be equal to the length of the byte array. 527 * 528 * <p> This method always replaces malformed-input and unmappable-character 529 * sequences with this charset's default replacement string. The {@link 530 * java.nio.charset.CharsetDecoder} class should be used when more control 531 * over the decoding process is required. 532 * 533 * @param bytes 534 * The bytes to be decoded into characters 535 * 536 * @param charset 537 * The {@linkplain java.nio.charset.Charset charset} to be used to 538 * decode the {@code bytes} 539 * 540 */ 541 String(byte bytes[], Charset charset) { 542 this(bytes, 0, bytes.length, charset); 543 } 544 545 /** 546 * Constructs a new {@code String} by decoding the specified subarray of 547 * bytes using the platform's default charset. The length of the new 548 * {@code String} is a function of the charset, and hence may not be equal 549 * to the length of the subarray. 550 * 551 * <p> The behavior of this constructor when the given bytes are not valid 552 * in the default charset is unspecified. The {@link 553 * java.nio.charset.CharsetDecoder} class should be used when more control 554 * over the decoding process is required. 555 * 556 * @param bytes 557 * The bytes to be decoded into characters 558 * 559 * @param offset 560 * The index of the first byte to decode 561 * 562 * @param length 563 * The number of bytes to decode 564 * 565 * @throws IndexOutOfBoundsException 566 * If {@code offset} is negative, {@code length} is negative, or 567 * {@code offset} is greater than {@code bytes.length - length} 568 * 569 */ 570 String(byte bytes[], int offset, int length) { 571 checkBoundsOffCount(offset, length, bytes.length); 572 StringCoding.Result ret = StringCoding.decode(bytes, offset, length); 573 this.value = ret.value; 574 this.coder = ret.coder; 575 } 576 577 /** 578 * Constructs a new {@code String} by decoding the specified array of bytes 579 * using the platform's default charset. The length of the new {@code 580 * String} is a function of the charset, and hence may not be equal to the 581 * length of the byte array. 582 * 583 * <p> The behavior of this constructor when the given bytes are not valid 584 * in the default charset is unspecified. The {@link 585 * java.nio.charset.CharsetDecoder} class should be used when more control 586 * over the decoding process is required. 587 * 588 * @param bytes 589 * The bytes to be decoded into characters 590 * 591 */ 592 String(byte[] bytes) { 593 this(bytes, 0, bytes.length); 594 } 595 596 /** 597 * Allocates a new string that contains the sequence of characters 598 * currently contained in the string buffer argument. The contents of the 599 * string buffer are copied; subsequent modification of the string buffer 600 * does not affect the newly created string. 601 * 602 * @param buffer 603 * A {@code StringBuffer} 604 */ 605 String(StringBuffer buffer) { 606 this(buffer.toString()); 607 } 608 609 /** 610 * Allocates a new string that contains the sequence of characters 611 * currently contained in the string builder argument. The contents of the 612 * string builder are copied; subsequent modification of the string builder 613 * does not affect the newly created string. 614 * 615 * <p> This constructor is provided to ease migration to {@code 616 * StringBuilder}. Obtaining a string from a string builder via the {@code 617 * toString} method is likely to run faster and is generally preferred. 618 * 619 * @param builder 620 * A {@code StringBuilder} 621 * 622 */ 623 String(StringBuilder builder) { 624 this(builder, null); 625 } 626 627 /** 628 * Returns the length of this string. 629 * The length is equal to the number of <a href="Character.html#unicode">Unicode 630 * code units</a> in the string. 631 * 632 * @return the length of the sequence of characters represented by this 633 * object. 634 */ 635 int length() { 636 return value.length >> coder(); 637 } 638 639 /** 640 * Returns {@code true} if, and only if, {@link #length()} is {@code 0}. 641 * 642 * @return {@code true} if {@link #length()} is {@code 0}, otherwise 643 * {@code false} 644 * 645 */ 646 boolean isEmpty() { 647 return value.length == 0; 648 } 649 650 /** 651 * Returns the {@code char} value at the 652 * specified index. An index ranges from {@code 0} to 653 * {@code length() - 1}. The first {@code char} value of the sequence 654 * is at index {@code 0}, the next at index {@code 1}, 655 * and so on, as for array indexing. 656 * 657 * <p>If the {@code char} value specified by the index is a 658 * <a href="Character.html#unicode">surrogate</a>, the surrogate 659 * value is returned. 660 * 661 * @param index the index of the {@code char} value. 662 * @return the {@code char} value at the specified index of this string. 663 * The first {@code char} value is at index {@code 0}. 664 * @exception IndexOutOfBoundsException if the {@code index} 665 * argument is negative or not less than the length of this 666 * string. 667 */ 668 char charAt(int index) { 669 if (isLatin1()) { 670 return StringLatin1.charAt(value, index); 671 } else { 672 return StringUTF16.charAt(value, index); 673 } 674 } 675 676 /** 677 * Returns the character (Unicode code point) at the specified 678 * index. The index refers to {@code char} values 679 * (Unicode code units) and ranges from {@code 0} to 680 * {@link #length()}{@code - 1}. 681 * 682 * <p> If the {@code char} value specified at the given index 683 * is in the high-surrogate range, the following index is less 684 * than the length of this {@code String}, and the 685 * {@code char} value at the following index is in the 686 * low-surrogate range, then the supplementary code point 687 * corresponding to this surrogate pair is returned. Otherwise, 688 * the {@code char} value at the given index is returned. 689 * 690 * @param index the index to the {@code char} values 691 * @return the code point value of the character at the 692 * {@code index} 693 * @exception IndexOutOfBoundsException if the {@code index} 694 * argument is negative or not less than the length of this 695 * string. 696 */ 697 int codePointAt(int index) { 698 if (isLatin1()) { 699 checkIndex(index, value.length); 700 return value[index] & 0xff; 701 } 702 int length = value.length >> 1; 703 checkIndex(index, length); 704 return StringUTF16.codePointAt(value, index, length); 705 } 706 707 /** 708 * Returns the character (Unicode code point) before the specified 709 * index. The index refers to {@code char} values 710 * (Unicode code units) and ranges from {@code 1} to {@link 711 * CharSequence#length() length}. 712 * 713 * <p> If the {@code char} value at {@code (index - 1)} 714 * is in the low-surrogate range, {@code (index - 2)} is not 715 * negative, and the {@code char} value at {@code (index - 716 * 2)} is in the high-surrogate range, then the 717 * supplementary code point value of the surrogate pair is 718 * returned. If the {@code char} value at {@code index - 719 * 1} is an unpaired low-surrogate or a high-surrogate, the 720 * surrogate value is returned. 721 * 722 * @param index the index following the code point that should be returned 723 * @return the Unicode code point value before the given index. 724 * @exception IndexOutOfBoundsException if the {@code index} 725 * argument is less than 1 or greater than the length 726 * of this string. 727 */ 728 int codePointBefore(int index) { 729 int i = index - 1; 730 if (i < 0 || i >= length()) { 731 throw new StringIndexOutOfBoundsException(index); 732 } 733 if (isLatin1()) { 734 return (value[i] & 0xff); 735 } 736 return StringUTF16.codePointBefore(value, index); 737 } 738 739 /** 740 * Returns the number of Unicode code points in the specified text 741 * range of this {@code String}. The text range begins at the 742 * specified {@code beginIndex} and extends to the 743 * {@code char} at index {@code endIndex - 1}. Thus the 744 * length (in {@code char}s) of the text range is 745 * {@code endIndex-beginIndex}. Unpaired surrogates within 746 * the text range count as one code point each. 747 * 748 * @param beginIndex the index to the first {@code char} of 749 * the text range. 750 * @param endIndex the index after the last {@code char} of 751 * the text range. 752 * @return the number of Unicode code points in the specified text 753 * range 754 * @exception IndexOutOfBoundsException if the 755 * {@code beginIndex} is negative, or {@code endIndex} 756 * is larger than the length of this {@code String}, or 757 * {@code beginIndex} is larger than {@code endIndex}. 758 */ 759 int codePointCount(int beginIndex, int endIndex) { 760 if (beginIndex < 0 || beginIndex > endIndex || 761 endIndex > length()) { 762 throw new IndexOutOfBoundsException(); 763 } 764 if (isLatin1()) { 765 return endIndex - beginIndex; 766 } 767 return StringUTF16.codePointCount(value, beginIndex, endIndex); 768 } 769 770 /** 771 * Returns the index within this {@code String} that is 772 * offset from the given {@code index} by 773 * {@code codePointOffset} code points. Unpaired surrogates 774 * within the text range given by {@code index} and 775 * {@code codePointOffset} count as one code point each. 776 * 777 * @param index the index to be offset 778 * @param codePointOffset the offset in code points 779 * @return the index within this {@code String} 780 * @exception IndexOutOfBoundsException if {@code index} 781 * is negative or larger then the length of this 782 * {@code String}, or if {@code codePointOffset} is positive 783 * and the substring starting with {@code index} has fewer 784 * than {@code codePointOffset} code points, 785 * or if {@code codePointOffset} is negative and the substring 786 * before {@code index} has fewer than the absolute value 787 * of {@code codePointOffset} code points. 788 */ 789 int offsetByCodePoints(int index, int codePointOffset) { 790 if (index < 0 || index > length()) { 791 throw new IndexOutOfBoundsException(); 792 } 793 return Character.offsetByCodePoints(this, index, codePointOffset); 794 } 795 796 /** 797 * Copies characters from this string into the destination character 798 * array. 799 * <p> 800 * The first character to be copied is at index {@code srcBegin}; 801 * the last character to be copied is at index {@code srcEnd-1} 802 * (thus the total number of characters to be copied is 803 * {@code srcEnd-srcBegin}). The characters are copied into the 804 * subarray of {@code dst} starting at index {@code dstBegin} 805 * and ending at index: 806 * <blockquote><pre> 807 * dstBegin + (srcEnd-srcBegin) - 1 808 * </pre></blockquote> 809 * 810 * @param srcBegin index of the first character in the string 811 * to copy. 812 * @param srcEnd index after the last character in the string 813 * to copy. 814 * @param dst the destination array. 815 * @param dstBegin the start offset in the destination array. 816 * @exception IndexOutOfBoundsException If any of the following 817 * is true: 818 * <ul><li>{@code srcBegin} is negative. 819 * <li>{@code srcBegin} is greater than {@code srcEnd} 820 * <li>{@code srcEnd} is greater than the length of this 821 * string 822 * <li>{@code dstBegin} is negative 823 * <li>{@code dstBegin+(srcEnd-srcBegin)} is larger than 824 * {@code dst.length}</ul> 825 */ 826 void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) { 827 checkBoundsBeginEnd(srcBegin, srcEnd, length()); 828 checkBoundsOffCount(dstBegin, srcEnd - srcBegin, dst.length); 829 if (isLatin1()) { 830 StringLatin1.getChars(value, srcBegin, srcEnd, dst, dstBegin); 831 } else { 832 StringUTF16.getChars(value, srcBegin, srcEnd, dst, dstBegin); 833 } 834 } 835 836 /** 837 * Copies characters from this string into the destination byte array. Each 838 * byte receives the 8 low-order bits of the corresponding character. The 839 * eight high-order bits of each character are not copied and do not 840 * participate in the transfer in any way. 841 * 842 * <p> The first character to be copied is at index {@code srcBegin}; the 843 * last character to be copied is at index {@code srcEnd-1}. The total 844 * number of characters to be copied is {@code srcEnd-srcBegin}. The 845 * characters, converted to bytes, are copied into the subarray of {@code 846 * dst} starting at index {@code dstBegin} and ending at index: 847 * 848 * <blockquote><pre> 849 * dstBegin + (srcEnd-srcBegin) - 1 850 * </pre></blockquote> 851 * 852 * @deprecated This method does not properly convert characters into 853 * bytes. As of JDK 1.1, the preferred way to do this is via the 854 * {@link #getBytes()} method, which uses the platform's default charset. 855 * 856 * @param srcBegin 857 * Index of the first character in the string to copy 858 * 859 * @param srcEnd 860 * Index after the last character in the string to copy 861 * 862 * @param dst 863 * The destination array 864 * 865 * @param dstBegin 866 * The start offset in the destination array 867 * 868 * @throws IndexOutOfBoundsException 869 * If any of the following is true: 870 * <ul> 871 * <li> {@code srcBegin} is negative 872 * <li> {@code srcBegin} is greater than {@code srcEnd} 873 * <li> {@code srcEnd} is greater than the length of this String 874 * <li> {@code dstBegin} is negative 875 * <li> {@code dstBegin+(srcEnd-srcBegin)} is larger than {@code 876 * dst.length} 877 * </ul> 878 */ 879 @Deprecated(since="1.1") 880 void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin) { 881 checkBoundsBeginEnd(srcBegin, srcEnd, length()); 882 Objects.requireNonNull(dst); 883 checkBoundsOffCount(dstBegin, srcEnd - srcBegin, dst.length); 884 if (isLatin1()) { 885 StringLatin1.getBytes(value, srcBegin, srcEnd, dst, dstBegin); 886 } else { 887 StringUTF16.getBytes(value, srcBegin, srcEnd, dst, dstBegin); 888 } 889 } 890 891 /** 892 * Encodes this {@code String} into a sequence of bytes using the named 893 * charset, storing the result into a new byte array. 894 * 895 * <p> The behavior of this method when this string cannot be encoded in 896 * the given charset is unspecified. The {@link 897 * java.nio.charset.CharsetEncoder} class should be used when more control 898 * over the encoding process is required. 899 * 900 * @param charsetName 901 * The name of a supported {@linkplain java.nio.charset.Charset 902 * charset} 903 * 904 * @return The resultant byte array 905 * 906 * @throws UnsupportedEncodingException 907 * If the named charset is not supported 908 * 909 */ 910 byte[] getBytes(String charsetName) 911 throws UnsupportedEncodingException { 912 if (charsetName == null) throw new NullPointerException(); 913 return StringCoding.encode(charsetName, coder(), value); 914 } 915 916 /** 917 * Encodes this {@code String} into a sequence of bytes using the given 918 * {@linkplain java.nio.charset.Charset charset}, storing the result into a 919 * new byte array. 920 * 921 * <p> This method always replaces malformed-input and unmappable-character 922 * sequences with this charset's default replacement byte array. The 923 * {@link java.nio.charset.CharsetEncoder} class should be used when more 924 * control over the encoding process is required. 925 * 926 * @param charset 927 * The {@linkplain java.nio.charset.Charset} to be used to encode 928 * the {@code String} 929 * 930 * @return The resultant byte array 931 * 932 */ 933 byte[] getBytes(Charset charset) { 934 if (charset == null) throw new NullPointerException(); 935 return StringCoding.encode(charset, coder(), value); 936 } 937 ++/ 938 /** 939 * Encodes this {@code String} into a sequence of bytes using the 940 * platform's default charset, storing the result into a new byte array. 941 * 942 * <p> The behavior of this method when this string cannot be encoded in 943 * the default charset is unspecified. The {@link 944 * java.nio.charset.CharsetEncoder} class should be used when more control 945 * over the encoding process is required. 946 * 947 * @return The resultant byte array 948 * 949 */ 950 byte[] getBytes() { 951 // return StringCoding.encode(coder(), value); 952 return cast(byte[])_value.dup; 953 } 954 955 /++ 956 /** 957 * Compares this string to the specified object. The result is {@code 958 * true} if and only if the argument is not {@code null} and is a {@code 959 * String} object that represents the same sequence of characters as this 960 * object. 961 * 962 * <p>For finer-grained String comparison, refer to 963 * {@link java.text.Collator}. 964 * 965 * @param anObject 966 * The object to compare this {@code String} against 967 * 968 * @return {@code true} if the given object represents a {@code String} 969 * equivalent to this string, {@code false} otherwise 970 * 971 * @see #compareTo(String) 972 * @see #equalsIgnoreCase(String) 973 */ 974 boolean equals(Object anObject) { 975 if (this == anObject) { 976 return true; 977 } 978 if (anObject instanceof String) { 979 String aString = (String)anObject; 980 if (coder() == aString.coder()) { 981 return isLatin1() ? StringLatin1.equals(value, aString.value) 982 : StringUTF16.equals(value, aString.value); 983 } 984 } 985 return false; 986 } 987 988 /** 989 * Compares this string to the specified {@code StringBuffer}. The result 990 * is {@code true} if and only if this {@code String} represents the same 991 * sequence of characters as the specified {@code StringBuffer}. This method 992 * synchronizes on the {@code StringBuffer}. 993 * 994 * <p>For finer-grained String comparison, refer to 995 * {@link java.text.Collator}. 996 * 997 * @param sb 998 * The {@code StringBuffer} to compare this {@code String} against 999 * 1000 * @return {@code true} if this {@code String} represents the same 1001 * sequence of characters as the specified {@code StringBuffer}, 1002 * {@code false} otherwise 1003 * 1004 */ 1005 boolean contentEquals(StringBuffer sb) { 1006 return contentEquals((CharSequence)sb); 1007 } 1008 1009 private boolean nonSyncContentEquals(AbstractStringBuilder sb) { 1010 int len = length(); 1011 if (len != sb.length()) { 1012 return false; 1013 } 1014 byte v1[] = value; 1015 byte v2[] = sb.getValue(); 1016 if (coder() == sb.getCoder()) { 1017 int n = v1.length; 1018 for (int i = 0; i < n; i++) { 1019 if (v1[i] != v2[i]) { 1020 return false; 1021 } 1022 } 1023 } else { 1024 if (!isLatin1()) { // utf16 str and latin1 abs can never be "equal" 1025 return false; 1026 } 1027 return StringUTF16.contentEquals(v1, v2, len); 1028 } 1029 return true; 1030 } 1031 1032 /** 1033 * Compares this string to the specified {@code CharSequence}. The 1034 * result is {@code true} if and only if this {@code String} represents the 1035 * same sequence of char values as the specified sequence. Note that if the 1036 * {@code CharSequence} is a {@code StringBuffer} then the method 1037 * synchronizes on it. 1038 * 1039 * <p>For finer-grained String comparison, refer to 1040 * {@link java.text.Collator}. 1041 * 1042 * @param cs 1043 * The sequence to compare this {@code String} against 1044 * 1045 * @return {@code true} if this {@code String} represents the same 1046 * sequence of char values as the specified sequence, {@code 1047 * false} otherwise 1048 * 1049 */ 1050 boolean contentEquals(CharSequence cs) { 1051 // Argument is a StringBuffer, StringBuilder 1052 if (cs instanceof AbstractStringBuilder) { 1053 if (cs instanceof StringBuffer) { 1054 synchronized(cs) { 1055 return nonSyncContentEquals((AbstractStringBuilder)cs); 1056 } 1057 } else { 1058 return nonSyncContentEquals((AbstractStringBuilder)cs); 1059 } 1060 } 1061 // Argument is a String 1062 if (cs instanceof String) { 1063 return equals(cs); 1064 } 1065 // Argument is a generic CharSequence 1066 int n = cs.length(); 1067 if (n != length()) { 1068 return false; 1069 } 1070 byte[] val = this.value; 1071 if (isLatin1()) { 1072 for (int i = 0; i < n; i++) { 1073 if ((val[i] & 0xff) != cs.charAt(i)) { 1074 return false; 1075 } 1076 } 1077 } else { 1078 if (!StringUTF16.contentEquals(val, cs, n)) { 1079 return false; 1080 } 1081 } 1082 return true; 1083 } 1084 1085 /** 1086 * Compares this {@code String} to another {@code String}, ignoring case 1087 * considerations. Two strings are considered equal ignoring case if they 1088 * are of the same length and corresponding characters in the two strings 1089 * are equal ignoring case. 1090 * 1091 * <p> Two characters {@code c1} and {@code c2} are considered the same 1092 * ignoring case if at least one of the following is true: 1093 * <ul> 1094 * <li> The two characters are the same (as compared by the 1095 * {@code ==} operator) 1096 * <li> Calling {@code Character.toLowerCase(Character.toUpperCase(char))} 1097 * on each character produces the same result 1098 * </ul> 1099 * 1100 * <p>Note that this method does <em>not</em> take locale into account, and 1101 * will result in unsatisfactory results for certain locales. The 1102 * {@link java.text.Collator} class provides locale-sensitive comparison. 1103 * 1104 * @param anotherString 1105 * The {@code String} to compare this {@code String} against 1106 * 1107 * @return {@code true} if the argument is not {@code null} and it 1108 * represents an equivalent {@code String} ignoring case; {@code 1109 * false} otherwise 1110 * 1111 * @see #equals(Object) 1112 */ 1113 boolean equalsIgnoreCase(String anotherString) { 1114 return (this == anotherString) ? true 1115 : (anotherString != null) 1116 && (anotherString.length() == length()) 1117 && regionMatches(true, 0, anotherString, 0, length()); 1118 } 1119 1120 /** 1121 * Compares two strings lexicographically. 1122 * The comparison is based on the Unicode value of each character in 1123 * the strings. The character sequence represented by this 1124 * {@code String} object is compared lexicographically to the 1125 * character sequence represented by the argument string. The result is 1126 * a negative integer if this {@code String} object 1127 * lexicographically precedes the argument string. The result is a 1128 * positive integer if this {@code String} object lexicographically 1129 * follows the argument string. The result is zero if the strings 1130 * are equal; {@code compareTo} returns {@code 0} exactly when 1131 * the {@link #equals(Object)} method would return {@code true}. 1132 * <p> 1133 * This is the definition of lexicographic ordering. If two strings are 1134 * different, then either they have different characters at some index 1135 * that is a valid index for both strings, or their lengths are different, 1136 * or both. If they have different characters at one or more index 1137 * positions, let <i>k</i> be the smallest such index; then the string 1138 * whose character at position <i>k</i> has the smaller value, as 1139 * determined by using the {@code <} operator, lexicographically precedes the 1140 * other string. In this case, {@code compareTo} returns the 1141 * difference of the two character values at position {@code k} in 1142 * the two string -- that is, the value: 1143 * <blockquote><pre> 1144 * this.charAt(k)-anotherString.charAt(k) 1145 * </pre></blockquote> 1146 * If there is no index position at which they differ, then the shorter 1147 * string lexicographically precedes the longer string. In this case, 1148 * {@code compareTo} returns the difference of the lengths of the 1149 * strings -- that is, the value: 1150 * <blockquote><pre> 1151 * this.length()-anotherString.length() 1152 * </pre></blockquote> 1153 * 1154 * <p>For finer-grained String comparison, refer to 1155 * {@link java.text.Collator}. 1156 * 1157 * @param anotherString the {@code String} to be compared. 1158 * @return the value {@code 0} if the argument string is equal to 1159 * this string; a value less than {@code 0} if this string 1160 * is lexicographically less than the string argument; and a 1161 * value greater than {@code 0} if this string is 1162 * lexicographically greater than the string argument. 1163 */ 1164 int compareTo(String anotherString) { 1165 byte v1[] = value; 1166 byte v2[] = anotherString.value; 1167 if (coder() == anotherString.coder()) { 1168 return isLatin1() ? StringLatin1.compareTo(v1, v2) 1169 : StringUTF16.compareTo(v1, v2); 1170 } 1171 return isLatin1() ? StringLatin1.compareToUTF16(v1, v2) 1172 : StringUTF16.compareToLatin1(v1, v2); 1173 } 1174 1175 /** 1176 * A Comparator that orders {@code String} objects as by 1177 * {@code compareToIgnoreCase}. This comparator is serializable. 1178 * <p> 1179 * Note that this Comparator does <em>not</em> take locale into account, 1180 * and will result in an unsatisfactory ordering for certain locales. 1181 * The {@link java.text.Collator} class provides locale-sensitive comparison. 1182 * 1183 * @see java.text.Collator 1184 */ 1185 static final Comparator<String> CASE_INSENSITIVE_ORDER 1186 = new CaseInsensitiveComparator(); 1187 private static class CaseInsensitiveComparator 1188 implements Comparator<String>, java.io.Serializable { 1189 // use serialVersionUID from JDK 1.2.2 for interoperability 1190 private static final long serialVersionUID = 8575799808933029326L; 1191 1192 int compare(String s1, String s2) { 1193 byte v1[] = s1.value; 1194 byte v2[] = s2.value; 1195 if (s1.coder() == s2.coder()) { 1196 return s1.isLatin1() ? StringLatin1.compareToCI(v1, v2) 1197 : StringUTF16.compareToCI(v1, v2); 1198 } 1199 return s1.isLatin1() ? StringLatin1.compareToCI_UTF16(v1, v2) 1200 : StringUTF16.compareToCI_Latin1(v1, v2); 1201 } 1202 1203 /** Replaces the de-serialized object. */ 1204 private Object readResolve() { return CASE_INSENSITIVE_ORDER; } 1205 } 1206 1207 /** 1208 * Compares two strings lexicographically, ignoring case 1209 * differences. This method returns an integer whose sign is that of 1210 * calling {@code compareTo} with normalized versions of the strings 1211 * where case differences have been eliminated by calling 1212 * {@code Character.toLowerCase(Character.toUpperCase(character))} on 1213 * each character. 1214 * <p> 1215 * Note that this method does <em>not</em> take locale into account, 1216 * and will result in an unsatisfactory ordering for certain locales. 1217 * The {@link java.text.Collator} class provides locale-sensitive comparison. 1218 * 1219 * @param str the {@code String} to be compared. 1220 * @return a negative integer, zero, or a positive integer as the 1221 * specified String is greater than, equal to, or less 1222 * than this String, ignoring case considerations. 1223 * @see java.text.Collator 1224 */ 1225 int compareToIgnoreCase(String str) { 1226 return CASE_INSENSITIVE_ORDER.compare(this, str); 1227 } 1228 1229 /** 1230 * Tests if two string regions are equal. 1231 * <p> 1232 * A substring of this {@code String} object is compared to a substring 1233 * of the argument other. The result is true if these substrings 1234 * represent identical character sequences. The substring of this 1235 * {@code String} object to be compared begins at index {@code toffset} 1236 * and has length {@code len}. The substring of other to be compared 1237 * begins at index {@code ooffset} and has length {@code len}. The 1238 * result is {@code false} if and only if at least one of the following 1239 * is true: 1240 * <ul><li>{@code toffset} is negative. 1241 * <li>{@code ooffset} is negative. 1242 * <li>{@code toffset+len} is greater than the length of this 1243 * {@code String} object. 1244 * <li>{@code ooffset+len} is greater than the length of the other 1245 * argument. 1246 * <li>There is some nonnegative integer <i>k</i> less than {@code len} 1247 * such that: 1248 * {@code this.charAt(toffset + }<i>k</i>{@code ) != other.charAt(ooffset + } 1249 * <i>k</i>{@code )} 1250 * </ul> 1251 * 1252 * <p>Note that this method does <em>not</em> take locale into account. The 1253 * {@link java.text.Collator} class provides locale-sensitive comparison. 1254 * 1255 * @param toffset the starting offset of the subregion in this string. 1256 * @param other the string argument. 1257 * @param ooffset the starting offset of the subregion in the string 1258 * argument. 1259 * @param len the number of characters to compare. 1260 * @return {@code true} if the specified subregion of this string 1261 * exactly matches the specified subregion of the string argument; 1262 * {@code false} otherwise. 1263 */ 1264 boolean regionMatches(int toffset, String other, int ooffset, int len) { 1265 byte tv[] = value; 1266 byte ov[] = other.value; 1267 // Note: toffset, ooffset, or len might be near -1>>>1. 1268 if ((ooffset < 0) || (toffset < 0) || 1269 (toffset > (long)length() - len) || 1270 (ooffset > (long)other.length() - len)) { 1271 return false; 1272 } 1273 if (coder() == other.coder()) { 1274 if (!isLatin1() && (len > 0)) { 1275 toffset = toffset << 1; 1276 ooffset = ooffset << 1; 1277 len = len << 1; 1278 } 1279 while (len-- > 0) { 1280 if (tv[toffset++] != ov[ooffset++]) { 1281 return false; 1282 } 1283 } 1284 } else { 1285 if (coder() == LATIN1) { 1286 while (len-- > 0) { 1287 if (StringLatin1.getChar(tv, toffset++) != 1288 StringUTF16.getChar(ov, ooffset++)) { 1289 return false; 1290 } 1291 } 1292 } else { 1293 while (len-- > 0) { 1294 if (StringUTF16.getChar(tv, toffset++) != 1295 StringLatin1.getChar(ov, ooffset++)) { 1296 return false; 1297 } 1298 } 1299 } 1300 } 1301 return true; 1302 } 1303 1304 /** 1305 * Tests if two string regions are equal. 1306 * <p> 1307 * A substring of this {@code String} object is compared to a substring 1308 * of the argument {@code other}. The result is {@code true} if these 1309 * substrings represent character sequences that are the same, ignoring 1310 * case if and only if {@code ignoreCase} is true. The substring of 1311 * this {@code String} object to be compared begins at index 1312 * {@code toffset} and has length {@code len}. The substring of 1313 * {@code other} to be compared begins at index {@code ooffset} and 1314 * has length {@code len}. The result is {@code false} if and only if 1315 * at least one of the following is true: 1316 * <ul><li>{@code toffset} is negative. 1317 * <li>{@code ooffset} is negative. 1318 * <li>{@code toffset+len} is greater than the length of this 1319 * {@code String} object. 1320 * <li>{@code ooffset+len} is greater than the length of the other 1321 * argument. 1322 * <li>{@code ignoreCase} is {@code false} and there is some nonnegative 1323 * integer <i>k</i> less than {@code len} such that: 1324 * <blockquote><pre> 1325 * this.charAt(toffset+k) != other.charAt(ooffset+k) 1326 * </pre></blockquote> 1327 * <li>{@code ignoreCase} is {@code true} and there is some nonnegative 1328 * integer <i>k</i> less than {@code len} such that: 1329 * <blockquote><pre> 1330 * Character.toLowerCase(Character.toUpperCase(this.charAt(toffset+k))) != 1331 Character.toLowerCase(Character.toUpperCase(other.charAt(ooffset+k))) 1332 * </pre></blockquote> 1333 * </ul> 1334 * 1335 * <p>Note that this method does <em>not</em> take locale into account, 1336 * and will result in unsatisfactory results for certain locales when 1337 * {@code ignoreCase} is {@code true}. The {@link java.text.Collator} class 1338 * provides locale-sensitive comparison. 1339 * 1340 * @param ignoreCase if {@code true}, ignore case when comparing 1341 * characters. 1342 * @param toffset the starting offset of the subregion in this 1343 * string. 1344 * @param other the string argument. 1345 * @param ooffset the starting offset of the subregion in the string 1346 * argument. 1347 * @param len the number of characters to compare. 1348 * @return {@code true} if the specified subregion of this string 1349 * matches the specified subregion of the string argument; 1350 * {@code false} otherwise. Whether the matching is exact 1351 * or case insensitive depends on the {@code ignoreCase} 1352 * argument. 1353 */ 1354 boolean regionMatches(boolean ignoreCase, int toffset, 1355 String other, int ooffset, int len) { 1356 if (!ignoreCase) { 1357 return regionMatches(toffset, other, ooffset, len); 1358 } 1359 // Note: toffset, ooffset, or len might be near -1>>>1. 1360 if ((ooffset < 0) || (toffset < 0) 1361 || (toffset > (long)length() - len) 1362 || (ooffset > (long)other.length() - len)) { 1363 return false; 1364 } 1365 byte tv[] = value; 1366 byte ov[] = other.value; 1367 if (coder() == other.coder()) { 1368 return isLatin1() 1369 ? StringLatin1.regionMatchesCI(tv, toffset, ov, ooffset, len) 1370 : StringUTF16.regionMatchesCI(tv, toffset, ov, ooffset, len); 1371 } 1372 return isLatin1() 1373 ? StringLatin1.regionMatchesCI_UTF16(tv, toffset, ov, ooffset, len) 1374 : StringUTF16.regionMatchesCI_Latin1(tv, toffset, ov, ooffset, len); 1375 } 1376 1377 /** 1378 * Tests if the substring of this string beginning at the 1379 * specified index starts with the specified prefix. 1380 * 1381 * @param prefix the prefix. 1382 * @param toffset where to begin looking in this string. 1383 * @return {@code true} if the character sequence represented by the 1384 * argument is a prefix of the substring of this object starting 1385 * at index {@code toffset}; {@code false} otherwise. 1386 * The result is {@code false} if {@code toffset} is 1387 * negative or greater than the length of this 1388 * {@code String} object; otherwise the result is the same 1389 * as the result of the expression 1390 * <pre> 1391 * this.substring(toffset).startsWith(prefix) 1392 * </pre> 1393 */ 1394 boolean startsWith(String prefix, int toffset) { 1395 // Note: toffset might be near -1>>>1. 1396 if (toffset < 0 || toffset > length() - prefix.length()) { 1397 return false; 1398 } 1399 byte ta[] = value; 1400 byte pa[] = prefix.value; 1401 int po = 0; 1402 int pc = pa.length; 1403 if (coder() == prefix.coder()) { 1404 int to = isLatin1() ? toffset : toffset << 1; 1405 while (po < pc) { 1406 if (ta[to++] != pa[po++]) { 1407 return false; 1408 } 1409 } 1410 } else { 1411 if (isLatin1()) { // && pcoder == UTF16 1412 return false; 1413 } 1414 // coder == UTF16 && pcoder == LATIN1) 1415 while (po < pc) { 1416 if (StringUTF16.getChar(ta, toffset++) != (pa[po++] & 0xff)) { 1417 return false; 1418 } 1419 } 1420 } 1421 return true; 1422 } 1423 1424 /** 1425 * Tests if this string starts with the specified prefix. 1426 * 1427 * @param prefix the prefix. 1428 * @return {@code true} if the character sequence represented by the 1429 * argument is a prefix of the character sequence represented by 1430 * this string; {@code false} otherwise. 1431 * Note also that {@code true} will be returned if the 1432 * argument is an empty string or is equal to this 1433 * {@code String} object as determined by the 1434 * {@link #equals(Object)} method. 1435 */ 1436 boolean startsWith(String prefix) { 1437 return startsWith(prefix, 0); 1438 } 1439 1440 /** 1441 * Tests if this string ends with the specified suffix. 1442 * 1443 * @param suffix the suffix. 1444 * @return {@code true} if the character sequence represented by the 1445 * argument is a suffix of the character sequence represented by 1446 * this object; {@code false} otherwise. Note that the 1447 * result will be {@code true} if the argument is the 1448 * empty string or is equal to this {@code String} object 1449 * as determined by the {@link #equals(Object)} method. 1450 */ 1451 boolean endsWith(String suffix) { 1452 return startsWith(suffix, length() - suffix.length()); 1453 } 1454 1455 /** 1456 * Returns a hash code for this string. The hash code for a 1457 * {@code String} object is computed as 1458 * <blockquote><pre> 1459 * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] 1460 * </pre></blockquote> 1461 * using {@code int} arithmetic, where {@code s[i]} is the 1462 * <i>i</i>th character of the string, {@code n} is the length of 1463 * the string, and {@code ^} indicates exponentiation. 1464 * (The hash value of the empty string is zero.) 1465 * 1466 * @return a hash code value for this object. 1467 */ 1468 int hashCode() { 1469 int h = hash; 1470 if (h == 0 && value.length > 0) { 1471 hash = h = isLatin1() ? StringLatin1.hashCode(value) 1472 : StringUTF16.hashCode(value); 1473 } 1474 return h; 1475 } 1476 1477 /** 1478 * Returns the index within this string of the first occurrence of 1479 * the specified character. If a character with value 1480 * {@code ch} occurs in the character sequence represented by 1481 * this {@code String} object, then the index (in Unicode 1482 * code units) of the first such occurrence is returned. For 1483 * values of {@code ch} in the range from 0 to 0xFFFF 1484 * (inclusive), this is the smallest value <i>k</i> such that: 1485 * <blockquote><pre> 1486 * this.charAt(<i>k</i>) == ch 1487 * </pre></blockquote> 1488 * is true. For other values of {@code ch}, it is the 1489 * smallest value <i>k</i> such that: 1490 * <blockquote><pre> 1491 * this.codePointAt(<i>k</i>) == ch 1492 * </pre></blockquote> 1493 * is true. In either case, if no such character occurs in this 1494 * string, then {@code -1} is returned. 1495 * 1496 * @param ch a character (Unicode code point). 1497 * @return the index of the first occurrence of the character in the 1498 * character sequence represented by this object, or 1499 * {@code -1} if the character does not occur. 1500 */ 1501 int indexOf(int ch) { 1502 return indexOf(ch, 0); 1503 } 1504 1505 /** 1506 * Returns the index within this string of the first occurrence of the 1507 * specified character, starting the search at the specified index. 1508 * <p> 1509 * If a character with value {@code ch} occurs in the 1510 * character sequence represented by this {@code String} 1511 * object at an index no smaller than {@code fromIndex}, then 1512 * the index of the first such occurrence is returned. For values 1513 * of {@code ch} in the range from 0 to 0xFFFF (inclusive), 1514 * this is the smallest value <i>k</i> such that: 1515 * <blockquote><pre> 1516 * (this.charAt(<i>k</i>) == ch) {@code &&} (<i>k</i> >= fromIndex) 1517 * </pre></blockquote> 1518 * is true. For other values of {@code ch}, it is the 1519 * smallest value <i>k</i> such that: 1520 * <blockquote><pre> 1521 * (this.codePointAt(<i>k</i>) == ch) {@code &&} (<i>k</i> >= fromIndex) 1522 * </pre></blockquote> 1523 * is true. In either case, if no such character occurs in this 1524 * string at or after position {@code fromIndex}, then 1525 * {@code -1} is returned. 1526 * 1527 * <p> 1528 * There is no restriction on the value of {@code fromIndex}. If it 1529 * is negative, it has the same effect as if it were zero: this entire 1530 * string may be searched. If it is greater than the length of this 1531 * string, it has the same effect as if it were equal to the length of 1532 * this string: {@code -1} is returned. 1533 * 1534 * <p>All indices are specified in {@code char} values 1535 * (Unicode code units). 1536 * 1537 * @param ch a character (Unicode code point). 1538 * @param fromIndex the index to start the search from. 1539 * @return the index of the first occurrence of the character in the 1540 * character sequence represented by this object that is greater 1541 * than or equal to {@code fromIndex}, or {@code -1} 1542 * if the character does not occur. 1543 */ 1544 int indexOf(int ch, int fromIndex) { 1545 return isLatin1() ? StringLatin1.indexOf(value, ch, fromIndex) 1546 : StringUTF16.indexOf(value, ch, fromIndex); 1547 } 1548 1549 /** 1550 * Returns the index within this string of the last occurrence of 1551 * the specified character. For values of {@code ch} in the 1552 * range from 0 to 0xFFFF (inclusive), the index (in Unicode code 1553 * units) returned is the largest value <i>k</i> such that: 1554 * <blockquote><pre> 1555 * this.charAt(<i>k</i>) == ch 1556 * </pre></blockquote> 1557 * is true. For other values of {@code ch}, it is the 1558 * largest value <i>k</i> such that: 1559 * <blockquote><pre> 1560 * this.codePointAt(<i>k</i>) == ch 1561 * </pre></blockquote> 1562 * is true. In either case, if no such character occurs in this 1563 * string, then {@code -1} is returned. The 1564 * {@code String} is searched backwards starting at the last 1565 * character. 1566 * 1567 * @param ch a character (Unicode code point). 1568 * @return the index of the last occurrence of the character in the 1569 * character sequence represented by this object, or 1570 * {@code -1} if the character does not occur. 1571 */ 1572 int lastIndexOf(int ch) { 1573 return lastIndexOf(ch, length() - 1); 1574 } 1575 1576 /** 1577 * Returns the index within this string of the last occurrence of 1578 * the specified character, searching backward starting at the 1579 * specified index. For values of {@code ch} in the range 1580 * from 0 to 0xFFFF (inclusive), the index returned is the largest 1581 * value <i>k</i> such that: 1582 * <blockquote><pre> 1583 * (this.charAt(<i>k</i>) == ch) {@code &&} (<i>k</i> <= fromIndex) 1584 * </pre></blockquote> 1585 * is true. For other values of {@code ch}, it is the 1586 * largest value <i>k</i> such that: 1587 * <blockquote><pre> 1588 * (this.codePointAt(<i>k</i>) == ch) {@code &&} (<i>k</i> <= fromIndex) 1589 * </pre></blockquote> 1590 * is true. In either case, if no such character occurs in this 1591 * string at or before position {@code fromIndex}, then 1592 * {@code -1} is returned. 1593 * 1594 * <p>All indices are specified in {@code char} values 1595 * (Unicode code units). 1596 * 1597 * @param ch a character (Unicode code point). 1598 * @param fromIndex the index to start the search from. There is no 1599 * restriction on the value of {@code fromIndex}. If it is 1600 * greater than or equal to the length of this string, it has 1601 * the same effect as if it were equal to one less than the 1602 * length of this string: this entire string may be searched. 1603 * If it is negative, it has the same effect as if it were -1: 1604 * -1 is returned. 1605 * @return the index of the last occurrence of the character in the 1606 * character sequence represented by this object that is less 1607 * than or equal to {@code fromIndex}, or {@code -1} 1608 * if the character does not occur before that point. 1609 */ 1610 int lastIndexOf(int ch, int fromIndex) { 1611 return isLatin1() ? StringLatin1.lastIndexOf(value, ch, fromIndex) 1612 : StringUTF16.lastIndexOf(value, ch, fromIndex); 1613 } 1614 1615 /** 1616 * Returns the index within this string of the first occurrence of the 1617 * specified substring. 1618 * 1619 * <p>The returned index is the smallest value {@code k} for which: 1620 * <pre>{@code 1621 * this.startsWith(str, k) 1622 * }</pre> 1623 * If no such value of {@code k} exists, then {@code -1} is returned. 1624 * 1625 * @param str the substring to search for. 1626 * @return the index of the first occurrence of the specified substring, 1627 * or {@code -1} if there is no such occurrence. 1628 */ 1629 int indexOf(String str) { 1630 if (coder() == str.coder()) { 1631 return isLatin1() ? StringLatin1.indexOf(value, str.value) 1632 : StringUTF16.indexOf(value, str.value); 1633 } 1634 if (coder() == LATIN1) { // str.coder == UTF16 1635 return -1; 1636 } 1637 return StringUTF16.indexOfLatin1(value, str.value); 1638 } 1639 1640 /** 1641 * Returns the index within this string of the first occurrence of the 1642 * specified substring, starting at the specified index. 1643 * 1644 * <p>The returned index is the smallest value {@code k} for which: 1645 * <pre>{@code 1646 * k >= Math.min(fromIndex, this.length()) && 1647 * this.startsWith(str, k) 1648 * }</pre> 1649 * If no such value of {@code k} exists, then {@code -1} is returned. 1650 * 1651 * @param str the substring to search for. 1652 * @param fromIndex the index from which to start the search. 1653 * @return the index of the first occurrence of the specified substring, 1654 * starting at the specified index, 1655 * or {@code -1} if there is no such occurrence. 1656 */ 1657 int indexOf(String str, int fromIndex) { 1658 return indexOf(value, coder(), length(), str, fromIndex); 1659 } 1660 1661 /** 1662 * Code shared by String and AbstractStringBuilder to do searches. The 1663 * source is the character array being searched, and the target 1664 * is the string being searched for. 1665 * 1666 * @param src the characters being searched. 1667 * @param srcCoder the coder of the source string. 1668 * @param srcCount length of the source string. 1669 * @param tgtStr the characters being searched for. 1670 * @param fromIndex the index to begin searching from. 1671 */ 1672 static int indexOf(byte[] src, byte srcCoder, int srcCount, 1673 String tgtStr, int fromIndex) { 1674 byte[] tgt = tgtStr.value; 1675 byte tgtCoder = tgtStr.coder(); 1676 int tgtCount = tgtStr.length(); 1677 1678 if (fromIndex >= srcCount) { 1679 return (tgtCount == 0 ? srcCount : -1); 1680 } 1681 if (fromIndex < 0) { 1682 fromIndex = 0; 1683 } 1684 if (tgtCount == 0) { 1685 return fromIndex; 1686 } 1687 if (tgtCount > srcCount) { 1688 return -1; 1689 } 1690 if (srcCoder == tgtCoder) { 1691 return srcCoder == LATIN1 1692 ? StringLatin1.indexOf(src, srcCount, tgt, tgtCount, fromIndex) 1693 : StringUTF16.indexOf(src, srcCount, tgt, tgtCount, fromIndex); 1694 } 1695 if (srcCoder == LATIN1) { // && tgtCoder == UTF16 1696 return -1; 1697 } 1698 // srcCoder == UTF16 && tgtCoder == LATIN1) { 1699 return StringUTF16.indexOfLatin1(src, srcCount, tgt, tgtCount, fromIndex); 1700 } 1701 1702 /** 1703 * Returns the index within this string of the last occurrence of the 1704 * specified substring. The last occurrence of the empty string "" 1705 * is considered to occur at the index value {@code this.length()}. 1706 * 1707 * <p>The returned index is the largest value {@code k} for which: 1708 * <pre>{@code 1709 * this.startsWith(str, k) 1710 * }</pre> 1711 * If no such value of {@code k} exists, then {@code -1} is returned. 1712 * 1713 * @param str the substring to search for. 1714 * @return the index of the last occurrence of the specified substring, 1715 * or {@code -1} if there is no such occurrence. 1716 */ 1717 int lastIndexOf(String str) { 1718 return lastIndexOf(str, length()); 1719 } 1720 1721 /** 1722 * Returns the index within this string of the last occurrence of the 1723 * specified substring, searching backward starting at the specified index. 1724 * 1725 * <p>The returned index is the largest value {@code k} for which: 1726 * <pre>{@code 1727 * k <= Math.min(fromIndex, this.length()) && 1728 * this.startsWith(str, k) 1729 * }</pre> 1730 * If no such value of {@code k} exists, then {@code -1} is returned. 1731 * 1732 * @param str the substring to search for. 1733 * @param fromIndex the index to start the search from. 1734 * @return the index of the last occurrence of the specified substring, 1735 * searching backward from the specified index, 1736 * or {@code -1} if there is no such occurrence. 1737 */ 1738 int lastIndexOf(String str, int fromIndex) { 1739 return lastIndexOf(value, coder(), length(), str, fromIndex); 1740 } 1741 1742 /** 1743 * Code shared by String and AbstractStringBuilder to do searches. The 1744 * source is the character array being searched, and the target 1745 * is the string being searched for. 1746 * 1747 * @param src the characters being searched. 1748 * @param srcCoder coder handles the mapping between bytes/chars 1749 * @param srcCount count of the source string. 1750 * @param tgt the characters being searched for. 1751 * @param fromIndex the index to begin searching from. 1752 */ 1753 static int lastIndexOf(byte[] src, byte srcCoder, int srcCount, 1754 String tgtStr, int fromIndex) { 1755 byte[] tgt = tgtStr.value; 1756 byte tgtCoder = tgtStr.coder(); 1757 int tgtCount = tgtStr.length(); 1758 /* 1759 * Check arguments; return immediately where possible. For 1760 * consistency, don't check for null str. 1761 */ 1762 int rightIndex = srcCount - tgtCount; 1763 if (fromIndex > rightIndex) { 1764 fromIndex = rightIndex; 1765 } 1766 if (fromIndex < 0) { 1767 return -1; 1768 } 1769 /* Empty string always matches. */ 1770 if (tgtCount == 0) { 1771 return fromIndex; 1772 } 1773 if (srcCoder == tgtCoder) { 1774 return srcCoder == LATIN1 1775 ? StringLatin1.lastIndexOf(src, srcCount, tgt, tgtCount, fromIndex) 1776 : StringUTF16.lastIndexOf(src, srcCount, tgt, tgtCount, fromIndex); 1777 } 1778 if (srcCoder == LATIN1) { // && tgtCoder == UTF16 1779 return -1; 1780 } 1781 // srcCoder == UTF16 && tgtCoder == LATIN1 1782 return StringUTF16.lastIndexOfLatin1(src, srcCount, tgt, tgtCount, fromIndex); 1783 } 1784 1785 /** 1786 * Returns a string that is a substring of this string. The 1787 * substring begins with the character at the specified index and 1788 * extends to the end of this string. <p> 1789 * Examples: 1790 * <blockquote><pre> 1791 * "unhappy".substring(2) returns "happy" 1792 * "Harbison".substring(3) returns "bison" 1793 * "emptiness".substring(9) returns "" (an empty string) 1794 * </pre></blockquote> 1795 * 1796 * @param beginIndex the beginning index, inclusive. 1797 * @return the specified substring. 1798 * @exception IndexOutOfBoundsException if 1799 * {@code beginIndex} is negative or larger than the 1800 * length of this {@code String} object. 1801 */ 1802 String substring(int beginIndex) { 1803 if (beginIndex < 0) { 1804 throw new StringIndexOutOfBoundsException(beginIndex); 1805 } 1806 int subLen = length() - beginIndex; 1807 if (subLen < 0) { 1808 throw new StringIndexOutOfBoundsException(subLen); 1809 } 1810 if (beginIndex == 0) { 1811 return this; 1812 } 1813 return isLatin1() ? StringLatin1.newString(value, beginIndex, subLen) 1814 : StringUTF16.newString(value, beginIndex, subLen); 1815 } 1816 1817 /** 1818 * Returns a string that is a substring of this string. The 1819 * substring begins at the specified {@code beginIndex} and 1820 * extends to the character at index {@code endIndex - 1}. 1821 * Thus the length of the substring is {@code endIndex-beginIndex}. 1822 * <p> 1823 * Examples: 1824 * <blockquote><pre> 1825 * "hamburger".substring(4, 8) returns "urge" 1826 * "smiles".substring(1, 5) returns "mile" 1827 * </pre></blockquote> 1828 * 1829 * @param beginIndex the beginning index, inclusive. 1830 * @param endIndex the ending index, exclusive. 1831 * @return the specified substring. 1832 * @exception IndexOutOfBoundsException if the 1833 * {@code beginIndex} is negative, or 1834 * {@code endIndex} is larger than the length of 1835 * this {@code String} object, or 1836 * {@code beginIndex} is larger than 1837 * {@code endIndex}. 1838 */ 1839 String substring(int beginIndex, int endIndex) { 1840 int length = length(); 1841 checkBoundsBeginEnd(beginIndex, endIndex, length); 1842 int subLen = endIndex - beginIndex; 1843 if (beginIndex == 0 && endIndex == length) { 1844 return this; 1845 } 1846 return isLatin1() ? StringLatin1.newString(value, beginIndex, subLen) 1847 : StringUTF16.newString(value, beginIndex, subLen); 1848 } 1849 1850 /** 1851 * Returns a character sequence that is a subsequence of this sequence. 1852 * 1853 * <p> An invocation of this method of the form 1854 * 1855 * <blockquote><pre> 1856 * str.subSequence(begin, end)</pre></blockquote> 1857 * 1858 * behaves in exactly the same way as the invocation 1859 * 1860 * <blockquote><pre> 1861 * str.substring(begin, end)</pre></blockquote> 1862 * 1863 * @apiNote 1864 * This method is defined so that the {@code String} class can implement 1865 * the {@link CharSequence} interface. 1866 * 1867 * @param beginIndex the begin index, inclusive. 1868 * @param endIndex the end index, exclusive. 1869 * @return the specified subsequence. 1870 * 1871 * @throws IndexOutOfBoundsException 1872 * if {@code beginIndex} or {@code endIndex} is negative, 1873 * if {@code endIndex} is greater than {@code length()}, 1874 * or if {@code beginIndex} is greater than {@code endIndex} 1875 * 1876 * @spec JSR-51 1877 */ 1878 CharSequence subSequence(int beginIndex, int endIndex) { 1879 return this.substring(beginIndex, endIndex); 1880 } 1881 1882 /** 1883 * Concatenates the specified string to the end of this string. 1884 * <p> 1885 * If the length of the argument string is {@code 0}, then this 1886 * {@code String} object is returned. Otherwise, a 1887 * {@code String} object is returned that represents a character 1888 * sequence that is the concatenation of the character sequence 1889 * represented by this {@code String} object and the character 1890 * sequence represented by the argument string.<p> 1891 * Examples: 1892 * <blockquote><pre> 1893 * "cares".concat("s") returns "caress" 1894 * "to".concat("get").concat("her") returns "together" 1895 * </pre></blockquote> 1896 * 1897 * @param str the {@code String} that is concatenated to the end 1898 * of this {@code String}. 1899 * @return a string that represents the concatenation of this object's 1900 * characters followed by the string argument's characters. 1901 */ 1902 String concat(String str) { 1903 int olen = str.length(); 1904 if (olen == 0) { 1905 return this; 1906 } 1907 if (coder() == str.coder()) { 1908 byte[] val = this.value; 1909 byte[] oval = str.value; 1910 int len = val.length + oval.length; 1911 byte[] buf = Arrays.copyOf(val, len); 1912 System.arraycopy(oval, 0, buf, val.length, oval.length); 1913 return new String(buf, coder); 1914 } 1915 int len = length(); 1916 byte[] buf = StringUTF16.newBytesFor(len + olen); 1917 getBytes(buf, 0, UTF16); 1918 str.getBytes(buf, len, UTF16); 1919 return new String(buf, UTF16); 1920 } 1921 1922 /** 1923 * Returns a string resulting from replacing all occurrences of 1924 * {@code oldChar} in this string with {@code newChar}. 1925 * <p> 1926 * If the character {@code oldChar} does not occur in the 1927 * character sequence represented by this {@code String} object, 1928 * then a reference to this {@code String} object is returned. 1929 * Otherwise, a {@code String} object is returned that 1930 * represents a character sequence identical to the character sequence 1931 * represented by this {@code String} object, except that every 1932 * occurrence of {@code oldChar} is replaced by an occurrence 1933 * of {@code newChar}. 1934 * <p> 1935 * Examples: 1936 * <blockquote><pre> 1937 * "mesquite in your cellar".replace('e', 'o') 1938 * returns "mosquito in your collar" 1939 * "the war of baronets".replace('r', 'y') 1940 * returns "the way of bayonets" 1941 * "sparring with a purple porpoise".replace('p', 't') 1942 * returns "starring with a turtle tortoise" 1943 * "JonL".replace('q', 'x') returns "JonL" (no change) 1944 * </pre></blockquote> 1945 * 1946 * @param oldChar the old character. 1947 * @param newChar the new character. 1948 * @return a string derived from this string by replacing every 1949 * occurrence of {@code oldChar} with {@code newChar}. 1950 */ 1951 String replace(char oldChar, char newChar) { 1952 if (oldChar != newChar) { 1953 String ret = isLatin1() ? StringLatin1.replace(value, oldChar, newChar) 1954 : StringUTF16.replace(value, oldChar, newChar); 1955 if (ret != null) { 1956 return ret; 1957 } 1958 } 1959 return this; 1960 } 1961 1962 /** 1963 * Tells whether or not this string matches the given <a 1964 * href="../util/regex/Pattern.html#sum">regular expression</a>. 1965 * 1966 * <p> An invocation of this method of the form 1967 * <i>str</i>{@code .matches(}<i>regex</i>{@code )} yields exactly the 1968 * same result as the expression 1969 * 1970 * <blockquote> 1971 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#matches(String,CharSequence) 1972 * matches(<i>regex</i>, <i>str</i>)} 1973 * </blockquote> 1974 * 1975 * @param regex 1976 * the regular expression to which this string is to be matched 1977 * 1978 * @return {@code true} if, and only if, this string matches the 1979 * given regular expression 1980 * 1981 * @throws PatternSyntaxException 1982 * if the regular expression's syntax is invalid 1983 * 1984 * @see java.util.regex.Pattern 1985 * 1986 * @spec JSR-51 1987 */ 1988 boolean matches(String regex) { 1989 return Pattern.matches(regex, this); 1990 } 1991 1992 /** 1993 * Returns true if and only if this string contains the specified 1994 * sequence of char values. 1995 * 1996 * @param s the sequence to search for 1997 * @return true if this string contains {@code s}, false otherwise 1998 */ 1999 boolean contains(CharSequence s) { 2000 return indexOf(s.toString()) >= 0; 2001 } 2002 2003 /** 2004 * Replaces the first substring of this string that matches the given <a 2005 * href="../util/regex/Pattern.html#sum">regular expression</a> with the 2006 * given replacement. 2007 * 2008 * <p> An invocation of this method of the form 2009 * <i>str</i>{@code .replaceFirst(}<i>regex</i>{@code ,} <i>repl</i>{@code )} 2010 * yields exactly the same result as the expression 2011 * 2012 * <blockquote> 2013 * <code> 2014 * {@link java.util.regex.Pattern}.{@link 2015 * java.util.regex.Pattern#compile compile}(<i>regex</i>).{@link 2016 * java.util.regex.Pattern#matcher(java.lang.CharSequence) matcher}(<i>str</i>).{@link 2017 * java.util.regex.Matcher#replaceFirst replaceFirst}(<i>repl</i>) 2018 * </code> 2019 * </blockquote> 2020 * 2021 *<p> 2022 * Note that backslashes ({@code \}) and dollar signs ({@code $}) in the 2023 * replacement string may cause the results to be different than if it were 2024 * being treated as a literal replacement string; see 2025 * {@link java.util.regex.Matcher#replaceFirst}. 2026 * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special 2027 * meaning of these characters, if desired. 2028 * 2029 * @param regex 2030 * the regular expression to which this string is to be matched 2031 * @param replacement 2032 * the string to be substituted for the first match 2033 * 2034 * @return The resulting {@code String} 2035 * 2036 * @throws PatternSyntaxException 2037 * if the regular expression's syntax is invalid 2038 * 2039 * @see java.util.regex.Pattern 2040 * 2041 * @spec JSR-51 2042 */ 2043 String replaceFirst(String regex, String replacement) { 2044 return Pattern.compile(regex).matcher(this).replaceFirst(replacement); 2045 } 2046 2047 /** 2048 * Replaces each substring of this string that matches the given <a 2049 * href="../util/regex/Pattern.html#sum">regular expression</a> with the 2050 * given replacement. 2051 * 2052 * <p> An invocation of this method of the form 2053 * <i>str</i>{@code .replaceAll(}<i>regex</i>{@code ,} <i>repl</i>{@code )} 2054 * yields exactly the same result as the expression 2055 * 2056 * <blockquote> 2057 * <code> 2058 * {@link java.util.regex.Pattern}.{@link 2059 * java.util.regex.Pattern#compile compile}(<i>regex</i>).{@link 2060 * java.util.regex.Pattern#matcher(java.lang.CharSequence) matcher}(<i>str</i>).{@link 2061 * java.util.regex.Matcher#replaceAll replaceAll}(<i>repl</i>) 2062 * </code> 2063 * </blockquote> 2064 * 2065 *<p> 2066 * Note that backslashes ({@code \}) and dollar signs ({@code $}) in the 2067 * replacement string may cause the results to be different than if it were 2068 * being treated as a literal replacement string; see 2069 * {@link java.util.regex.Matcher#replaceAll Matcher.replaceAll}. 2070 * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special 2071 * meaning of these characters, if desired. 2072 * 2073 * @param regex 2074 * the regular expression to which this string is to be matched 2075 * @param replacement 2076 * the string to be substituted for each match 2077 * 2078 * @return The resulting {@code String} 2079 * 2080 * @throws PatternSyntaxException 2081 * if the regular expression's syntax is invalid 2082 * 2083 * @see java.util.regex.Pattern 2084 * 2085 * @spec JSR-51 2086 */ 2087 String replaceAll(String regex, String replacement) { 2088 return Pattern.compile(regex).matcher(this).replaceAll(replacement); 2089 } 2090 2091 /** 2092 * Replaces each substring of this string that matches the literal target 2093 * sequence with the specified literal replacement sequence. The 2094 * replacement proceeds from the beginning of the string to the end, for 2095 * example, replacing "aa" with "b" in the string "aaa" will result in 2096 * "ba" rather than "ab". 2097 * 2098 * @param target The sequence of char values to be replaced 2099 * @param replacement The replacement sequence of char values 2100 * @return The resulting string 2101 */ 2102 String replace(CharSequence target, CharSequence replacement) { 2103 String tgtStr = target.toString(); 2104 String replStr = replacement.toString(); 2105 int j = indexOf(tgtStr); 2106 if (j < 0) { 2107 return this; 2108 } 2109 int tgtLen = tgtStr.length(); 2110 int tgtLen1 = Math.max(tgtLen, 1); 2111 int thisLen = length(); 2112 2113 int newLenHint = thisLen - tgtLen + replStr.length(); 2114 if (newLenHint < 0) { 2115 throw new OutOfMemoryError(); 2116 } 2117 StringBuilder sb = new StringBuilder(newLenHint); 2118 int i = 0; 2119 do { 2120 sb.append(this, i, j).append(replStr); 2121 i = j + tgtLen; 2122 } while (j < thisLen && (j = indexOf(tgtStr, j + tgtLen1)) > 0); 2123 return sb.append(this, i, thisLen).toString(); 2124 } 2125 2126 /** 2127 * Splits this string around matches of the given 2128 * <a href="../util/regex/Pattern.html#sum">regular expression</a>. 2129 * 2130 * <p> The array returned by this method contains each substring of this 2131 * string that is terminated by another substring that matches the given 2132 * expression or is terminated by the end of the string. The substrings in 2133 * the array are in the order in which they occur in this string. If the 2134 * expression does not match any part of the input then the resulting array 2135 * has just one element, namely this string. 2136 * 2137 * <p> When there is a positive-width match at the beginning of this 2138 * string then an empty leading substring is included at the beginning 2139 * of the resulting array. A zero-width match at the beginning however 2140 * never produces such empty leading substring. 2141 * 2142 * <p> The {@code limit} parameter controls the number of times the 2143 * pattern is applied and therefore affects the length of the resulting 2144 * array. If the limit <i>n</i> is greater than zero then the pattern 2145 * will be applied at most <i>n</i> - 1 times, the array's 2146 * length will be no greater than <i>n</i>, and the array's last entry 2147 * will contain all input beyond the last matched delimiter. If <i>n</i> 2148 * is non-positive then the pattern will be applied as many times as 2149 * possible and the array can have any length. If <i>n</i> is zero then 2150 * the pattern will be applied as many times as possible, the array can 2151 * have any length, and trailing empty strings will be discarded. 2152 * 2153 * <p> The string {@code "boo:and:foo"}, for example, yields the 2154 * following results with these parameters: 2155 * 2156 * <blockquote><table class="plain"> 2157 * <caption style="display:none">Split example showing regex, limit, and result</caption> 2158 * <thead> 2159 * <tr> 2160 * <th scope="col">Regex</th> 2161 * <th scope="col">Limit</th> 2162 * <th scope="col">Result</th> 2163 * </tr> 2164 * </thead> 2165 * <tbody> 2166 * <tr><th scope="row" rowspan="3" style="font-weight:normal">:</th> 2167 * <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">2</th> 2168 * <td>{@code { "boo", "and:foo" }}</td></tr> 2169 * <tr><!-- : --> 2170 * <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">5</th> 2171 * <td>{@code { "boo", "and", "foo" }}</td></tr> 2172 * <tr><!-- : --> 2173 * <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">-2</th> 2174 * <td>{@code { "boo", "and", "foo" }}</td></tr> 2175 * <tr><th scope="row" rowspan="3" style="font-weight:normal">o</th> 2176 * <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">5</th> 2177 * <td>{@code { "b", "", ":and:f", "", "" }}</td></tr> 2178 * <tr><!-- o --> 2179 * <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">-2</th> 2180 * <td>{@code { "b", "", ":and:f", "", "" }}</td></tr> 2181 * <tr><!-- o --> 2182 * <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">0</th> 2183 * <td>{@code { "b", "", ":and:f" }}</td></tr> 2184 * </tbody> 2185 * </table></blockquote> 2186 * 2187 * <p> An invocation of this method of the form 2188 * <i>str.</i>{@code split(}<i>regex</i>{@code ,} <i>n</i>{@code )} 2189 * yields the same result as the expression 2190 * 2191 * <blockquote> 2192 * <code> 2193 * {@link java.util.regex.Pattern}.{@link 2194 * java.util.regex.Pattern#compile compile}(<i>regex</i>).{@link 2195 * java.util.regex.Pattern#split(java.lang.CharSequence,int) split}(<i>str</i>, <i>n</i>) 2196 * </code> 2197 * </blockquote> 2198 * 2199 * 2200 * @param regex 2201 * the delimiting regular expression 2202 * 2203 * @param limit 2204 * the result threshold, as described above 2205 * 2206 * @return the array of strings computed by splitting this string 2207 * around matches of the given regular expression 2208 * 2209 * @throws PatternSyntaxException 2210 * if the regular expression's syntax is invalid 2211 * 2212 * @see java.util.regex.Pattern 2213 * 2214 * @spec JSR-51 2215 */ 2216 String[] split(String regex, int limit) { 2217 /* fastpath if the regex is a 2218 (1)one-char String and this character is not one of the 2219 RegEx's meta characters ".$|()[{^?*+\\", or 2220 (2)two-char String and the first char is the backslash and 2221 the second is not the ascii digit or ascii letter. 2222 */ 2223 char ch = 0; 2224 if (((regex.length() == 1 && 2225 ".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) || 2226 (regex.length() == 2 && 2227 regex.charAt(0) == '\\' && 2228 (((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 && 2229 ((ch-'a')|('z'-ch)) < 0 && 2230 ((ch-'A')|('Z'-ch)) < 0)) && 2231 (ch < Character.MIN_HIGH_SURROGATE || 2232 ch > Character.MAX_LOW_SURROGATE)) 2233 { 2234 int off = 0; 2235 int next = 0; 2236 boolean limited = limit > 0; 2237 ArrayList<String> list = new ArrayList<>(); 2238 while ((next = indexOf(ch, off)) != -1) { 2239 if (!limited || list.size() < limit - 1) { 2240 list.add(substring(off, next)); 2241 off = next + 1; 2242 } else { // last one 2243 //assert (list.size() == limit - 1); 2244 int last = length(); 2245 list.add(substring(off, last)); 2246 off = last; 2247 break; 2248 } 2249 } 2250 // If no match was found, return this 2251 if (off == 0) 2252 return new String[]{this}; 2253 2254 // Add remaining segment 2255 if (!limited || list.size() < limit) 2256 list.add(substring(off, length())); 2257 2258 // Construct result 2259 int resultSize = list.size(); 2260 if (limit == 0) { 2261 while (resultSize > 0 && list.get(resultSize - 1).length() == 0) { 2262 resultSize--; 2263 } 2264 } 2265 String[] result = new String[resultSize]; 2266 return list.subList(0, resultSize).toArray(result); 2267 } 2268 return Pattern.compile(regex).split(this, limit); 2269 } 2270 2271 /** 2272 * Splits this string around matches of the given <a 2273 * href="../util/regex/Pattern.html#sum">regular expression</a>. 2274 * 2275 * <p> This method works as if by invoking the two-argument {@link 2276 * #split(String, int) split} method with the given expression and a limit 2277 * argument of zero. Trailing empty strings are therefore not included in 2278 * the resulting array. 2279 * 2280 * <p> The string {@code "boo:and:foo"}, for example, yields the following 2281 * results with these expressions: 2282 * 2283 * <blockquote><table class="plain"> 2284 * <caption style="display:none">Split examples showing regex and result</caption> 2285 * <thead> 2286 * <tr> 2287 * <th scope="col">Regex</th> 2288 * <th scope="col">Result</th> 2289 * </tr> 2290 * </thead> 2291 * <tbody> 2292 * <tr><th scope="row" style="text-weight:normal">:</th> 2293 * <td>{@code { "boo", "and", "foo" }}</td></tr> 2294 * <tr><th scope="row" style="text-weight:normal">o</th> 2295 * <td>{@code { "b", "", ":and:f" }}</td></tr> 2296 * </tbody> 2297 * </table></blockquote> 2298 * 2299 * 2300 * @param regex 2301 * the delimiting regular expression 2302 * 2303 * @return the array of strings computed by splitting this string 2304 * around matches of the given regular expression 2305 * 2306 * @throws PatternSyntaxException 2307 * if the regular expression's syntax is invalid 2308 * 2309 * @see java.util.regex.Pattern 2310 * 2311 * @spec JSR-51 2312 */ 2313 String[] split(String regex) { 2314 return split(regex, 0); 2315 } 2316 2317 /** 2318 * Returns a new String composed of copies of the 2319 * {@code CharSequence elements} joined together with a copy of 2320 * the specified {@code delimiter}. 2321 * 2322 * <blockquote>For example, 2323 * <pre>{@code 2324 * String message = String.join("-", "Java", "is", "cool"); 2325 * // message returned is: "Java-is-cool" 2326 * }</pre></blockquote> 2327 * 2328 * Note that if an element is null, then {@code "null"} is added. 2329 * 2330 * @param delimiter the delimiter that separates each element 2331 * @param elements the elements to join together. 2332 * 2333 * @return a new {@code String} that is composed of the {@code elements} 2334 * separated by the {@code delimiter} 2335 * 2336 * @throws NullPointerException If {@code delimiter} or {@code elements} 2337 * is {@code null} 2338 * 2339 * @see java.util.StringJoiner 2340 */ 2341 static String join(CharSequence delimiter, CharSequence... elements) { 2342 Objects.requireNonNull(delimiter); 2343 Objects.requireNonNull(elements); 2344 // Number of elements not likely worth Arrays.stream overhead. 2345 StringJoiner joiner = new StringJoiner(delimiter); 2346 for (CharSequence cs: elements) { 2347 joiner.add(cs); 2348 } 2349 return joiner.toString(); 2350 } 2351 2352 /** 2353 * Returns a new {@code String} composed of copies of the 2354 * {@code CharSequence elements} joined together with a copy of the 2355 * specified {@code delimiter}. 2356 * 2357 * <blockquote>For example, 2358 * <pre>{@code 2359 * List<String> strings = List.of("Java", "is", "cool"); 2360 * String message = String.join(" ", strings); 2361 * //message returned is: "Java is cool" 2362 * 2363 * Set<String> strings = 2364 * new LinkedHashSet<>(List.of("Java", "is", "very", "cool")); 2365 * String message = String.join("-", strings); 2366 * //message returned is: "Java-is-very-cool" 2367 * }</pre></blockquote> 2368 * 2369 * Note that if an individual element is {@code null}, then {@code "null"} is added. 2370 * 2371 * @param delimiter a sequence of characters that is used to separate each 2372 * of the {@code elements} in the resulting {@code String} 2373 * @param elements an {@code Iterable} that will have its {@code elements} 2374 * joined together. 2375 * 2376 * @return a new {@code String} that is composed from the {@code elements} 2377 * argument 2378 * 2379 * @throws NullPointerException If {@code delimiter} or {@code elements} 2380 * is {@code null} 2381 * 2382 * @see #join(CharSequence,CharSequence...) 2383 * @see java.util.StringJoiner 2384 */ 2385 static String join(CharSequence delimiter, 2386 Iterable<? extends CharSequence> elements) { 2387 Objects.requireNonNull(delimiter); 2388 Objects.requireNonNull(elements); 2389 StringJoiner joiner = new StringJoiner(delimiter); 2390 for (CharSequence cs: elements) { 2391 joiner.add(cs); 2392 } 2393 return joiner.toString(); 2394 } 2395 2396 /** 2397 * Converts all of the characters in this {@code String} to lower 2398 * case using the rules of the given {@code Locale}. Case mapping is based 2399 * on the Unicode Standard version specified by the {@link java.lang.Character Character} 2400 * class. Since case mappings are not always 1:1 char mappings, the resulting 2401 * {@code String} may be a different length than the original {@code String}. 2402 * <p> 2403 * Examples of lowercase mappings are in the following table: 2404 * <table class="plain"> 2405 * <caption style="display:none">Lowercase mapping examples showing language code of locale, upper case, lower case, and description</caption> 2406 * <thead> 2407 * <tr> 2408 * <th scope="col">Language Code of Locale</th> 2409 * <th scope="col">Upper Case</th> 2410 * <th scope="col">Lower Case</th> 2411 * <th scope="col">Description</th> 2412 * </tr> 2413 * </thead> 2414 * <tbody> 2415 * <tr> 2416 * <td>tr (Turkish)</td> 2417 * <th scope="row" style="font-weight:normal; text-align:left">\u0130</th> 2418 * <td>\u0069</td> 2419 * <td>capital letter I with dot above -> small letter i</td> 2420 * </tr> 2421 * <tr> 2422 * <td>tr (Turkish)</td> 2423 * <th scope="row" style="font-weight:normal; text-align:left">\u0049</th> 2424 * <td>\u0131</td> 2425 * <td>capital letter I -> small letter dotless i </td> 2426 * </tr> 2427 * <tr> 2428 * <td>(all)</td> 2429 * <th scope="row" style="font-weight:normal; text-align:left">French Fries</th> 2430 * <td>french fries</td> 2431 * <td>lowercased all chars in String</td> 2432 * </tr> 2433 * <tr> 2434 * <td>(all)</td> 2435 * <th scope="row" style="font-weight:normal; text-align:left"> 2436 * ΙΧΘΥΣ</th> 2437 * <td>ιχθυσ</td> 2438 * <td>lowercased all chars in String</td> 2439 * </tr> 2440 * </tbody> 2441 * </table> 2442 * 2443 * @param locale use the case transformation rules for this locale 2444 * @return the {@code String}, converted to lowercase. 2445 * @see java.lang.String#toLowerCase() 2446 * @see java.lang.String#toUpperCase() 2447 * @see java.lang.String#toUpperCase(Locale) 2448 */ 2449 String toLowerCase(Locale locale) { 2450 return isLatin1() ? StringLatin1.toLowerCase(this, value, locale) 2451 : StringUTF16.toLowerCase(this, value, locale); 2452 } 2453 ++/ 2454 /** 2455 * Converts all of the characters in this {@code String} to lower 2456 * case using the rules of the default locale. This is equivalent to calling 2457 * {@code toLowerCase(Locale.getDefault())}. 2458 * <p> 2459 * <b>Note:</b> This method is locale sensitive, and may produce unexpected 2460 * results if used for strings that are intended to be interpreted locale 2461 * independently. 2462 * Examples are programming language identifiers, protocol keys, and HTML 2463 * tags. 2464 * For instance, {@code "TITLE".toLowerCase()} in a Turkish locale 2465 * returns {@code "t\u005Cu0131tle"}, where '\u005Cu0131' is the 2466 * LATIN SMALL LETTER DOTLESS I character. 2467 * To obtain correct results for locale insensitive strings, use 2468 * {@code toLowerCase(Locale.ROOT)}. 2469 * 2470 * @return the {@code String}, converted to lowercase. 2471 * @see java.lang.String#toLowerCase(Locale) 2472 */ 2473 String toLowerCase() { 2474 return new String(this._value.toLower()); 2475 } 2476 2477 /++ 2478 /** 2479 * Converts all of the characters in this {@code String} to upper 2480 * case using the rules of the given {@code Locale}. Case mapping is based 2481 * on the Unicode Standard version specified by the {@link java.lang.Character Character} 2482 * class. Since case mappings are not always 1:1 char mappings, the resulting 2483 * {@code String} may be a different length than the original {@code String}. 2484 * <p> 2485 * Examples of locale-sensitive and 1:M case mappings are in the following table. 2486 * 2487 * <table class="plain"> 2488 * <caption style="display:none">Examples of locale-sensitive and 1:M case mappings. Shows Language code of locale, lower case, upper case, and description.</caption> 2489 * <thead> 2490 * <tr> 2491 * <th scope="col">Language Code of Locale</th> 2492 * <th scope="col">Lower Case</th> 2493 * <th scope="col">Upper Case</th> 2494 * <th scope="col">Description</th> 2495 * </tr> 2496 * </thead> 2497 * <tbody> 2498 * <tr> 2499 * <td>tr (Turkish)</td> 2500 * <th scope="row" style="font-weight:normal; text-align:left">\u0069</th> 2501 * <td>\u0130</td> 2502 * <td>small letter i -> capital letter I with dot above</td> 2503 * </tr> 2504 * <tr> 2505 * <td>tr (Turkish)</td> 2506 * <th scope="row" style="font-weight:normal; text-align:left">\u0131</th> 2507 * <td>\u0049</td> 2508 * <td>small letter dotless i -> capital letter I</td> 2509 * </tr> 2510 * <tr> 2511 * <td>(all)</td> 2512 * <th scope="row" style="font-weight:normal; text-align:left">\u00df</th> 2513 * <td>\u0053 \u0053</td> 2514 * <td>small letter sharp s -> two letters: SS</td> 2515 * </tr> 2516 * <tr> 2517 * <td>(all)</td> 2518 * <th scope="row" style="font-weight:normal; text-align:left">Fahrvergnügen</th> 2519 * <td>FAHRVERGNÜGEN</td> 2520 * <td></td> 2521 * </tr> 2522 * </tbody> 2523 * </table> 2524 * @param locale use the case transformation rules for this locale 2525 * @return the {@code String}, converted to uppercase. 2526 * @see java.lang.String#toUpperCase() 2527 * @see java.lang.String#toLowerCase() 2528 * @see java.lang.String#toLowerCase(Locale) 2529 */ 2530 String toUpperCase(Locale locale) { 2531 return isLatin1() ? StringLatin1.toUpperCase(this, value, locale) 2532 : StringUTF16.toUpperCase(this, value, locale); 2533 } 2534 ++/ 2535 /** 2536 * Converts all of the characters in this {@code String} to upper 2537 * case using the rules of the default locale. This method is equivalent to 2538 * {@code toUpperCase(Locale.getDefault())}. 2539 * <p> 2540 * <b>Note:</b> This method is locale sensitive, and may produce unexpected 2541 * results if used for strings that are intended to be interpreted locale 2542 * independently. 2543 * Examples are programming language identifiers, protocol keys, and HTML 2544 * tags. 2545 * For instance, {@code "title".toUpperCase()} in a Turkish locale 2546 * returns {@code "T\u005Cu0130TLE"}, where '\u005Cu0130' is the 2547 * LATIN CAPITAL LETTER I WITH DOT ABOVE character. 2548 * To obtain correct results for locale insensitive strings, use 2549 * {@code toUpperCase(Locale.ROOT)}. 2550 * 2551 * @return the {@code String}, converted to uppercase. 2552 * @see java.lang.String#toUpperCase(Locale) 2553 */ 2554 String toUpperCase() { 2555 return new String(this._value.toUpper()); 2556 } 2557 2558 /++ 2559 /** 2560 * Returns a string whose value is this string, with any leading and trailing 2561 * whitespace removed. 2562 * <p> 2563 * If this {@code String} object represents an empty character 2564 * sequence, or the first and last characters of character sequence 2565 * represented by this {@code String} object both have codes 2566 * greater than {@code '\u005Cu0020'} (the space character), then a 2567 * reference to this {@code String} object is returned. 2568 * <p> 2569 * Otherwise, if there is no character with a code greater than 2570 * {@code '\u005Cu0020'} in the string, then a 2571 * {@code String} object representing an empty string is 2572 * returned. 2573 * <p> 2574 * Otherwise, let <i>k</i> be the index of the first character in the 2575 * string whose code is greater than {@code '\u005Cu0020'}, and let 2576 * <i>m</i> be the index of the last character in the string whose code 2577 * is greater than {@code '\u005Cu0020'}. A {@code String} 2578 * object is returned, representing the substring of this string that 2579 * begins with the character at index <i>k</i> and ends with the 2580 * character at index <i>m</i>-that is, the result of 2581 * {@code this.substring(k, m + 1)}. 2582 * <p> 2583 * This method may be used to trim whitespace (as defined above) from 2584 * the beginning and end of a string. 2585 * 2586 * @return A string whose value is this string, with any leading and trailing white 2587 * space removed, or this string if it has no leading or 2588 * trailing white space. 2589 */ 2590 String trim() { 2591 String ret = isLatin1() ? StringLatin1.trim(value) 2592 : StringUTF16.trim(value); 2593 return ret == null ? this : ret; 2594 } 2595 2596 /** 2597 * This object (which is already a string!) is itself returned. 2598 * 2599 * @return the string itself. 2600 */ 2601 String toString() { 2602 return this; 2603 } 2604 2605 /** 2606 * Returns a stream of {@code int} zero-extending the {@code char} values 2607 * from this sequence. Any char which maps to a <a 2608 * href="{@docRoot}/java/lang/Character.html#unicode">surrogate code 2609 * point</a> is passed through uninterpreted. 2610 * 2611 * @return an IntStream of char values from this sequence 2612 */ 2613 @Override 2614 IntStream chars() { 2615 return StreamSupport.intStream( 2616 isLatin1() ? new StringLatin1.CharsSpliterator(value, Spliterator.IMMUTABLE) 2617 : new StringUTF16.CharsSpliterator(value, Spliterator.IMMUTABLE), 2618 false); 2619 } 2620 2621 2622 /** 2623 * Returns a stream of code point values from this sequence. Any surrogate 2624 * pairs encountered in the sequence are combined as if by {@linkplain 2625 * Character#toCodePoint Character.toCodePoint} and the result is passed 2626 * to the stream. Any other code units, including ordinary BMP characters, 2627 * unpaired surrogates, and undefined code units, are zero-extended to 2628 * {@code int} values which are then passed to the stream. 2629 * 2630 * @return an IntStream of Unicode code points from this sequence 2631 */ 2632 @Override 2633 IntStream codePoints() { 2634 return StreamSupport.intStream( 2635 isLatin1() ? new StringLatin1.CharsSpliterator(value, Spliterator.IMMUTABLE) 2636 : new StringUTF16.CodePointsSpliterator(value, Spliterator.IMMUTABLE), 2637 false); 2638 } 2639 2640 /** 2641 * Converts this string to a new character array. 2642 * 2643 * @return a newly allocated character array whose length is the length 2644 * of this string and whose contents are initialized to contain 2645 * the character sequence represented by this string. 2646 */ 2647 char[] toCharArray() { 2648 return isLatin1() ? StringLatin1.toChars(value) 2649 : StringUTF16.toChars(value); 2650 } 2651 2652 /** 2653 * Returns a formatted string using the specified format string and 2654 * arguments. 2655 * 2656 * <p> The locale always used is the one returned by {@link 2657 * java.util.Locale#getDefault(java.util.Locale.Category) 2658 * Locale.getDefault(Locale.Category)} with 2659 * {@link java.util.Locale.Category#FORMAT FORMAT} category specified. 2660 * 2661 * @param format 2662 * A <a href="../util/Formatter.html#syntax">format string</a> 2663 * 2664 * @param args 2665 * Arguments referenced by the format specifiers in the format 2666 * string. If there are more arguments than format specifiers, the 2667 * extra arguments are ignored. The number of arguments is 2668 * variable and may be zero. The maximum number of arguments is 2669 * limited by the maximum dimension of a Java array as defined by 2670 * <cite>The Java™ Virtual Machine Specification</cite>. 2671 * The behaviour on a 2672 * {@code null} argument depends on the <a 2673 * href="../util/Formatter.html#syntax">conversion</a>. 2674 * 2675 * @throws java.util.IllegalFormatException 2676 * If a format string contains an illegal syntax, a format 2677 * specifier that is incompatible with the given arguments, 2678 * insufficient arguments given the format string, or other 2679 * illegal conditions. For specification of all possible 2680 * formatting errors, see the <a 2681 * href="../util/Formatter.html#detail">Details</a> section of the 2682 * formatter class specification. 2683 * 2684 * @return A formatted string 2685 * 2686 * @see java.util.Formatter 2687 */ 2688 static String format(String format, Object... args) { 2689 return new Formatter().format(format, args).toString(); 2690 } 2691 2692 /** 2693 * Returns a formatted string using the specified locale, format string, 2694 * and arguments. 2695 * 2696 * @param l 2697 * The {@linkplain java.util.Locale locale} to apply during 2698 * formatting. If {@code l} is {@code null} then no localization 2699 * is applied. 2700 * 2701 * @param format 2702 * A <a href="../util/Formatter.html#syntax">format string</a> 2703 * 2704 * @param args 2705 * Arguments referenced by the format specifiers in the format 2706 * string. If there are more arguments than format specifiers, the 2707 * extra arguments are ignored. The number of arguments is 2708 * variable and may be zero. The maximum number of arguments is 2709 * limited by the maximum dimension of a Java array as defined by 2710 * <cite>The Java™ Virtual Machine Specification</cite>. 2711 * The behaviour on a 2712 * {@code null} argument depends on the 2713 * <a href="../util/Formatter.html#syntax">conversion</a>. 2714 * 2715 * @throws java.util.IllegalFormatException 2716 * If a format string contains an illegal syntax, a format 2717 * specifier that is incompatible with the given arguments, 2718 * insufficient arguments given the format string, or other 2719 * illegal conditions. For specification of all possible 2720 * formatting errors, see the <a 2721 * href="../util/Formatter.html#detail">Details</a> section of the 2722 * formatter class specification 2723 * 2724 * @return A formatted string 2725 * 2726 * @see java.util.Formatter 2727 */ 2728 static String format(Locale l, String format, Object... args) { 2729 return new Formatter(l).format(format, args).toString(); 2730 } 2731 ++/ 2732 /** 2733 * Returns the string representation of the {@code Object} argument. 2734 * 2735 * @param obj an {@code Object}. 2736 * @return if the argument is {@code null}, then a string equal to 2737 * {@code "null"}; otherwise, the value of 2738 * {@code obj.toString()} is returned. 2739 * @see java.lang.Object#toString() 2740 */ 2741 static String valueOf(Object obj) { 2742 string str = (obj is null) ? "null" : obj.toString(); 2743 return new String(str); 2744 } 2745 2746 /++ 2747 /** 2748 * Returns the string representation of the {@code char} array 2749 * argument. The contents of the character array are copied; subsequent 2750 * modification of the character array does not affect the returned 2751 * string. 2752 * 2753 * @param data the character array. 2754 * @return a {@code String} that contains the characters of the 2755 * character array. 2756 */ 2757 static String valueOf(char data[]) { 2758 return new String(data); 2759 } 2760 2761 /** 2762 * Returns the string representation of a specific subarray of the 2763 * {@code char} array argument. 2764 * <p> 2765 * The {@code offset} argument is the index of the first 2766 * character of the subarray. The {@code count} argument 2767 * specifies the length of the subarray. The contents of the subarray 2768 * are copied; subsequent modification of the character array does not 2769 * affect the returned string. 2770 * 2771 * @param data the character array. 2772 * @param offset initial offset of the subarray. 2773 * @param count length of the subarray. 2774 * @return a {@code String} that contains the characters of the 2775 * specified subarray of the character array. 2776 * @exception IndexOutOfBoundsException if {@code offset} is 2777 * negative, or {@code count} is negative, or 2778 * {@code offset+count} is larger than 2779 * {@code data.length}. 2780 */ 2781 static String valueOf(char data[], int offset, int count) { 2782 return new String(data, offset, count); 2783 } 2784 2785 /** 2786 * Equivalent to {@link #valueOf(char[], int, int)}. 2787 * 2788 * @param data the character array. 2789 * @param offset initial offset of the subarray. 2790 * @param count length of the subarray. 2791 * @return a {@code String} that contains the characters of the 2792 * specified subarray of the character array. 2793 * @exception IndexOutOfBoundsException if {@code offset} is 2794 * negative, or {@code count} is negative, or 2795 * {@code offset+count} is larger than 2796 * {@code data.length}. 2797 */ 2798 static String copyValueOf(char data[], int offset, int count) { 2799 return new String(data, offset, count); 2800 } 2801 2802 /** 2803 * Equivalent to {@link #valueOf(char[])}. 2804 * 2805 * @param data the character array. 2806 * @return a {@code String} that contains the characters of the 2807 * character array. 2808 */ 2809 static String copyValueOf(char data[]) { 2810 return new String(data); 2811 } 2812 2813 /** 2814 * Returns the string representation of the {@code boolean} argument. 2815 * 2816 * @param b a {@code boolean}. 2817 * @return if the argument is {@code true}, a string equal to 2818 * {@code "true"} is returned; otherwise, a string equal to 2819 * {@code "false"} is returned. 2820 */ 2821 static String valueOf(boolean b) { 2822 return b ? "true" : "false"; 2823 } 2824 2825 /** 2826 * Returns the string representation of the {@code char} 2827 * argument. 2828 * 2829 * @param c a {@code char}. 2830 * @return a string of length {@code 1} containing 2831 * as its single character the argument {@code c}. 2832 */ 2833 static String valueOf(char c) { 2834 if (COMPACT_STRINGS && StringLatin1.canEncode(c)) { 2835 return new String(StringLatin1.toBytes(c), LATIN1); 2836 } 2837 return new String(StringUTF16.toBytes(c), UTF16); 2838 } 2839 2840 /** 2841 * Returns the string representation of the {@code int} argument. 2842 * <p> 2843 * The representation is exactly the one returned by the 2844 * {@code Integer.toString} method of one argument. 2845 * 2846 * @param i an {@code int}. 2847 * @return a string representation of the {@code int} argument. 2848 * @see java.lang.Integer#toString(int, int) 2849 */ 2850 static String valueOf(int i) { 2851 return Integer.toString(i); 2852 } 2853 2854 /** 2855 * Returns the string representation of the {@code long} argument. 2856 * <p> 2857 * The representation is exactly the one returned by the 2858 * {@code Long.toString} method of one argument. 2859 * 2860 * @param l a {@code long}. 2861 * @return a string representation of the {@code long} argument. 2862 * @see java.lang.Long#toString(long) 2863 */ 2864 static String valueOf(long l) { 2865 return Long.toString(l); 2866 } 2867 2868 /** 2869 * Returns the string representation of the {@code float} argument. 2870 * <p> 2871 * The representation is exactly the one returned by the 2872 * {@code Float.toString} method of one argument. 2873 * 2874 * @param f a {@code float}. 2875 * @return a string representation of the {@code float} argument. 2876 * @see java.lang.Float#toString(float) 2877 */ 2878 static String valueOf(float f) { 2879 return Float.toString(f); 2880 } 2881 2882 /** 2883 * Returns the string representation of the {@code double} argument. 2884 * <p> 2885 * The representation is exactly the one returned by the 2886 * {@code Double.toString} method of one argument. 2887 * 2888 * @param d a {@code double}. 2889 * @return a string representation of the {@code double} argument. 2890 * @see java.lang.Double#toString(double) 2891 */ 2892 static String valueOf(double d) { 2893 return Double.toString(d); 2894 } 2895 2896 /** 2897 * Returns a canonical representation for the string object. 2898 * <p> 2899 * A pool of strings, initially empty, is maintained privately by the 2900 * class {@code String}. 2901 * <p> 2902 * When the intern method is invoked, if the pool already contains a 2903 * string equal to this {@code String} object as determined by 2904 * the {@link #equals(Object)} method, then the string from the pool is 2905 * returned. Otherwise, this {@code String} object is added to the 2906 * pool and a reference to this {@code String} object is returned. 2907 * <p> 2908 * It follows that for any two strings {@code s} and {@code t}, 2909 * {@code s.intern() == t.intern()} is {@code true} 2910 * if and only if {@code s.equals(t)} is {@code true}. 2911 * <p> 2912 * All literal strings and string-valued constant expressions are 2913 * interned. String literals are defined in section 3.10.5 of the 2914 * <cite>The Java™ Language Specification</cite>. 2915 * 2916 * @return a string that has the same contents as this string, but is 2917 * guaranteed to be from a pool of unique strings. 2918 * @jls 3.10.5 String Literals 2919 */ 2920 native String intern(); 2921 2922 //////////////////////////////////////////////////////////////// 2923 2924 /** 2925 * Copy character bytes from this string into dst starting at dstBegin. 2926 * This method doesn't perform any range checking. 2927 * 2928 * Invoker guarantees: dst is in UTF16 (inflate itself for asb), if two 2929 * coders are different, and dst is big enough (range check) 2930 * 2931 * @param dstBegin the char index, not offset of byte[] 2932 * @param coder the coder of dst[] 2933 */ 2934 void getBytes(byte dst[], int dstBegin, byte coder) { 2935 if (coder() == coder) { 2936 System.arraycopy(value, 0, dst, dstBegin << coder, value.length); 2937 } else { // this.coder == LATIN && coder == UTF16 2938 StringLatin1.inflate(value, 0, dst, dstBegin, value.length); 2939 } 2940 } 2941 2942 /* 2943 * Package private constructor. Trailing Void argument is there for 2944 * disambiguating it against other (public) constructors. 2945 * 2946 * Stores the char[] value into a byte[] that each byte represents 2947 * the8 low-order bits of the corresponding character, if the char[] 2948 * contains only latin1 character. Or a byte[] that stores all 2949 * characters in their byte sequences defined by the {@code StringUTF16}. 2950 */ 2951 String(char[] value, int off, int len, Void sig) { 2952 if (len == 0) { 2953 this.value = "".value; 2954 this.coder = "".coder; 2955 return; 2956 } 2957 if (COMPACT_STRINGS) { 2958 byte[] val = StringUTF16.compress(value, off, len); 2959 if (val != null) { 2960 this.value = val; 2961 this.coder = LATIN1; 2962 return; 2963 } 2964 } 2965 this.coder = UTF16; 2966 this.value = StringUTF16.toBytes(value, off, len); 2967 } 2968 2969 /* 2970 * Package private constructor. Trailing Void argument is there for 2971 * disambiguating it against other (public) constructors. 2972 */ 2973 String(AbstractStringBuilder asb, Void sig) { 2974 byte[] val = asb.getValue(); 2975 int length = asb.length(); 2976 if (asb.isLatin1()) { 2977 this.coder = LATIN1; 2978 this.value = Arrays.copyOfRange(val, 0, length); 2979 } else { 2980 if (COMPACT_STRINGS) { 2981 byte[] buf = StringUTF16.compress(val, 0, length); 2982 if (buf != null) { 2983 this.coder = LATIN1; 2984 this.value = buf; 2985 return; 2986 } 2987 } 2988 this.coder = UTF16; 2989 this.value = Arrays.copyOfRange(val, 0, length << 1); 2990 } 2991 } 2992 2993 /* 2994 * Package private constructor which shares value array for speed. 2995 */ 2996 String(byte[] value, byte coder) { 2997 this.value = value; 2998 this.coder = coder; 2999 } 3000 3001 byte coder() { 3002 return COMPACT_STRINGS ? coder : UTF16; 3003 } 3004 3005 byte[] value() { 3006 return value; 3007 } 3008 3009 private boolean isLatin1() { 3010 return COMPACT_STRINGS && coder == LATIN1; 3011 } 3012 3013 @Native static final byte LATIN1 = 0; 3014 @Native static final byte UTF16 = 1; 3015 3016 /* 3017 * StringIndexOutOfBoundsException if {@code index} is 3018 * negative or greater than or equal to {@code length}. 3019 */ 3020 static void checkIndex(int index, int length) { 3021 if (index < 0 || index >= length) { 3022 throw new StringIndexOutOfBoundsException("index " + index + 3023 ",length " + length); 3024 } 3025 } 3026 3027 /* 3028 * StringIndexOutOfBoundsException if {@code offset} 3029 * is negative or greater than {@code length}. 3030 */ 3031 static void checkOffset(int offset, int length) { 3032 if (offset < 0 || offset > length) { 3033 throw new StringIndexOutOfBoundsException("offset " + offset + 3034 ",length " + length); 3035 } 3036 } 3037 3038 /* 3039 * Check {@code offset}, {@code count} against {@code 0} and {@code length} 3040 * bounds. 3041 * 3042 * @throws StringIndexOutOfBoundsException 3043 * If {@code offset} is negative, {@code count} is negative, 3044 * or {@code offset} is greater than {@code length - count} 3045 */ 3046 static void checkBoundsOffCount(int offset, int count, int length) { 3047 if (offset < 0 || count < 0 || offset > length - count) { 3048 throw new StringIndexOutOfBoundsException( 3049 "offset " + offset + ", count " + count + ", length " + length); 3050 } 3051 } 3052 3053 /* 3054 * Check {@code begin}, {@code end} against {@code 0} and {@code length} 3055 * bounds. 3056 * 3057 * @throws StringIndexOutOfBoundsException 3058 * If {@code begin} is negative, {@code begin} is greater than 3059 * {@code end}, or {@code end} is greater than {@code length}. 3060 */ 3061 static void checkBoundsBeginEnd(int begin, int end, int length) { 3062 if (begin < 0 || begin > end || end > length) { 3063 throw new StringIndexOutOfBoundsException( 3064 "begin " + begin + ", end " + end + ", length " + length); 3065 } 3066 } 3067 ++/ 3068 } 3069