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