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