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