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