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