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