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