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 n = v1.length; 1014 if (n != sb.length()) { 1015 return false; 1016 } 1017 for (int i = 0; i < n; i++) { 1018 if (v1[i] != v2[i]) { 1019 return false; 1020 } 1021 } 1022 return true; 1023 } 1024 1025 /** 1026 * Compares this string to the specified {@code CharSequence}. The 1027 * result is {@code true} if and only if this {@code String} represents the 1028 * same sequence of char values as the specified sequence. Note that if the 1029 * {@code CharSequence} is a {@code StringBuffer} then the method 1030 * synchronizes on it. 1031 * 1032 * @param cs 1033 * The sequence to compare this {@code String} against 1034 * 1035 * @return {@code true} if this {@code String} represents the same 1036 * sequence of char values as the specified sequence, {@code 1037 * false} otherwise 1038 * 1039 * @since 1.5 1040 */ 1041 public boolean contentEquals(CharSequence cs) { 1042 // Argument is a StringBuffer, StringBuilder 1043 if (cs instanceof AbstractStringBuilder) { 1044 if (cs instanceof StringBuffer) { 1045 synchronized(cs) { 1046 return nonSyncContentEquals((AbstractStringBuilder)cs); 1047 } 1048 } else { 1049 return nonSyncContentEquals((AbstractStringBuilder)cs); 1050 } 1051 } 1052 // Argument is a String 1053 if (cs.equals(this)) 1054 return true; 1055 // Argument is a generic CharSequence 1056 char v1[] = value; 1057 int n = v1.length; 1058 if (n != cs.length()) { 1059 return false; 1060 } 1061 for (int i = 0; i < n; i++) { 1062 if (v1[i] != cs.charAt(i)) { 1063 return false; 1064 } 1065 } 1066 return true; 1067 } 1068 1069 /** 1070 * Compares this {@code String} to another {@code String}, ignoring case 1071 * considerations. Two strings are considered equal ignoring case if they 1072 * are of the same length and corresponding characters in the two strings 1073 * are equal ignoring case. 1074 * 1075 * <p> Two characters {@code c1} and {@code c2} are considered the same 1076 * ignoring case if at least one of the following is true: 1077 * <ul> 1078 * <li> The two characters are the same (as compared by the 1079 * {@code ==} operator) 1080 * <li> Applying the method {@link 1081 * java.lang.Character#toUpperCase(char)} to each character 1082 * produces the same result 1083 * <li> Applying the method {@link 1084 * java.lang.Character#toLowerCase(char)} to each character 1085 * produces the same result 1086 * </ul> 1087 * 1088 * @param anotherString 1089 * The {@code String} to compare this {@code String} against 1090 * 1091 * @return {@code true} if the argument is not {@code null} and it 1092 * represents an equivalent {@code String} ignoring case; {@code 1093 * false} otherwise 1094 * 1095 * @see #equals(Object) 1096 */ 1097 public boolean equalsIgnoreCase(String anotherString) { 1098 return (this == anotherString) ? true 1099 : (anotherString != null) 1100 && (anotherString.value.length == value.length) 1101 && regionMatches(true, 0, anotherString, 0, value.length); 1102 } 1103 1104 /** 1105 * Compares two strings lexicographically. 1106 * The comparison is based on the Unicode value of each character in 1107 * the strings. The character sequence represented by this 1108 * {@code String} object is compared lexicographically to the 1109 * character sequence represented by the argument string. The result is 1110 * a negative integer if this {@code String} object 1111 * lexicographically precedes the argument string. The result is a 1112 * positive integer if this {@code String} object lexicographically 1113 * follows the argument string. The result is zero if the strings 1114 * are equal; {@code compareTo} returns {@code 0} exactly when 1115 * the {@link #equals(Object)} method would return {@code true}. 1116 * <p> 1117 * This is the definition of lexicographic ordering. If two strings are 1118 * different, then either they have different characters at some index 1119 * that is a valid index for both strings, or their lengths are different, 1120 * or both. If they have different characters at one or more index 1121 * positions, let <i>k</i> be the smallest such index; then the string 1122 * whose character at position <i>k</i> has the smaller value, as 1123 * determined by using the < operator, lexicographically precedes the 1124 * other string. In this case, {@code compareTo} returns the 1125 * difference of the two character values at position {@code k} in 1126 * the two string -- that is, the value: 1127 * <blockquote><pre> 1128 * this.charAt(k)-anotherString.charAt(k) 1129 * </pre></blockquote> 1130 * If there is no index position at which they differ, then the shorter 1131 * string lexicographically precedes the longer string. In this case, 1132 * {@code compareTo} returns the difference of the lengths of the 1133 * strings -- that is, the value: 1134 * <blockquote><pre> 1135 * this.length()-anotherString.length() 1136 * </pre></blockquote> 1137 * 1138 * @param anotherString the {@code String} to be compared. 1139 * @return the value {@code 0} if the argument string is equal to 1140 * this string; a value less than {@code 0} if this string 1141 * is lexicographically less than the string argument; and a 1142 * value greater than {@code 0} if this string is 1143 * lexicographically greater than the string argument. 1144 */ 1145 public int compareTo(String anotherString) { 1146 int len1 = value.length; 1147 int len2 = anotherString.value.length; 1148 int lim = Math.min(len1, len2); 1149 char v1[] = value; 1150 char v2[] = anotherString.value; 1151 1152 int k = 0; 1153 while (k < lim) { 1154 char c1 = v1[k]; 1155 char c2 = v2[k]; 1156 if (c1 != c2) { 1157 return c1 - c2; 1158 } 1159 k++; 1160 } 1161 return len1 - len2; 1162 } 1163 1164 /** 1165 * A Comparator that orders {@code String} objects as by 1166 * {@code compareToIgnoreCase}. This comparator is serializable. 1167 * <p> 1168 * Note that this Comparator does <em>not</em> take locale into account, 1169 * and will result in an unsatisfactory ordering for certain locales. 1170 * The java.text package provides <em>Collators</em> to allow 1171 * locale-sensitive ordering. 1172 * 1173 * @see java.text.Collator#compare(String, String) 1174 * @since 1.2 1175 */ 1176 public static final Comparator<String> CASE_INSENSITIVE_ORDER 1177 = new CaseInsensitiveComparator(); 1178 private static class CaseInsensitiveComparator 1179 implements Comparator<String>, java.io.Serializable { 1180 // use serialVersionUID from JDK 1.2.2 for interoperability 1181 private static final long serialVersionUID = 8575799808933029326L; 1182 1183 public int compare(String s1, String s2) { 1184 int n1 = s1.length(); 1185 int n2 = s2.length(); 1186 int min = Math.min(n1, n2); 1187 for (int i = 0; i < min; i++) { 1188 char c1 = s1.charAt(i); 1189 char c2 = s2.charAt(i); 1190 if (c1 != c2) { 1191 c1 = Character.toUpperCase(c1); 1192 c2 = Character.toUpperCase(c2); 1193 if (c1 != c2) { 1194 c1 = Character.toLowerCase(c1); 1195 c2 = Character.toLowerCase(c2); 1196 if (c1 != c2) { 1197 // No overflow because of numeric promotion 1198 return c1 - c2; 1199 } 1200 } 1201 } 1202 } 1203 return n1 - n2; 1204 } 1205 1206 /** Replaces the de-serialized object. */ 1207 private Object readResolve() { return CASE_INSENSITIVE_ORDER; } 1208 } 1209 1210 /** 1211 * Compares two strings lexicographically, ignoring case 1212 * differences. This method returns an integer whose sign is that of 1213 * calling {@code compareTo} with normalized versions of the strings 1214 * where case differences have been eliminated by calling 1215 * {@code Character.toLowerCase(Character.toUpperCase(character))} on 1216 * each character. 1217 * <p> 1218 * Note that this method does <em>not</em> take locale into account, 1219 * and will result in an unsatisfactory ordering for certain locales. 1220 * The java.text package provides <em>collators</em> to allow 1221 * locale-sensitive ordering. 1222 * 1223 * @param str the {@code String} to be compared. 1224 * @return a negative integer, zero, or a positive integer as the 1225 * specified String is greater than, equal to, or less 1226 * than this String, ignoring case considerations. 1227 * @see java.text.Collator#compare(String, String) 1228 * @since 1.2 1229 */ 1230 public int compareToIgnoreCase(String str) { 1231 return CASE_INSENSITIVE_ORDER.compare(this, str); 1232 } 1233 1234 /** 1235 * Tests if two string regions are equal. 1236 * <p> 1237 * A substring of this {@code String} object is compared to a substring 1238 * of the argument other. The result is true if these substrings 1239 * represent identical character sequences. The substring of this 1240 * {@code String} object to be compared begins at index {@code toffset} 1241 * and has length {@code len}. The substring of other to be compared 1242 * begins at index {@code ooffset} and has length {@code len}. The 1243 * result is {@code false} if and only if at least one of the following 1244 * is true: 1245 * <ul><li>{@code toffset} is negative. 1246 * <li>{@code ooffset} is negative. 1247 * <li>{@code toffset+len} is greater than the length of this 1248 * {@code String} object. 1249 * <li>{@code ooffset+len} is greater than the length of the other 1250 * argument. 1251 * <li>There is some nonnegative integer <i>k</i> less than {@code len} 1252 * such that: 1253 * {@code this.charAt(toffset + }<i>k</i>{@code ) != other.charAt(ooffset + } 1254 * <i>k</i>{@code )} 1255 * </ul> 1256 * 1257 * @param toffset the starting offset of the subregion in this string. 1258 * @param other the string argument. 1259 * @param ooffset the starting offset of the subregion in the string 1260 * argument. 1261 * @param len the number of characters to compare. 1262 * @return {@code true} if the specified subregion of this string 1263 * exactly matches the specified subregion of the string argument; 1264 * {@code false} otherwise. 1265 */ 1266 public boolean regionMatches(int toffset, String other, int ooffset, 1267 int len) { 1268 char ta[] = value; 1269 int to = toffset; 1270 char pa[] = other.value; 1271 int po = ooffset; 1272 // Note: toffset, ooffset, or len might be near -1>>>1. 1273 if ((ooffset < 0) || (toffset < 0) 1274 || (toffset > (long)value.length - len) 1275 || (ooffset > (long)other.value.length - len)) { 1276 return false; 1277 } 1278 while (len-- > 0) { 1279 if (ta[to++] != pa[po++]) { 1280 return false; 1281 } 1282 } 1283 return true; 1284 } 1285 1286 /** 1287 * Tests if two string regions are equal. 1288 * <p> 1289 * A substring of this {@code String} object is compared to a substring 1290 * of the argument {@code other}. The result is {@code true} if these 1291 * substrings represent character sequences that are the same, ignoring 1292 * case if and only if {@code ignoreCase} is true. The substring of 1293 * this {@code String} object to be compared begins at index 1294 * {@code toffset} and has length {@code len}. The substring of 1295 * {@code other} to be compared begins at index {@code ooffset} and 1296 * has length {@code len}. The result is {@code false} if and only if 1297 * at least one of the following is true: 1298 * <ul><li>{@code toffset} is negative. 1299 * <li>{@code ooffset} is negative. 1300 * <li>{@code toffset+len} is greater than the length of this 1301 * {@code String} object. 1302 * <li>{@code ooffset+len} is greater than the length of the other 1303 * argument. 1304 * <li>{@code ignoreCase} is {@code false} and there is some nonnegative 1305 * integer <i>k</i> less than {@code len} such that: 1306 * <blockquote><pre> 1307 * this.charAt(toffset+k) != other.charAt(ooffset+k) 1308 * </pre></blockquote> 1309 * <li>{@code ignoreCase} is {@code true} and there is some nonnegative 1310 * integer <i>k</i> less than {@code len} such that: 1311 * <blockquote><pre> 1312 * Character.toLowerCase(this.charAt(toffset+k)) != 1313 Character.toLowerCase(other.charAt(ooffset+k)) 1314 * </pre></blockquote> 1315 * and: 1316 * <blockquote><pre> 1317 * Character.toUpperCase(this.charAt(toffset+k)) != 1318 * Character.toUpperCase(other.charAt(ooffset+k)) 1319 * </pre></blockquote> 1320 * </ul> 1321 * 1322 * @param ignoreCase if {@code true}, ignore case when comparing 1323 * characters. 1324 * @param toffset the starting offset of the subregion in this 1325 * string. 1326 * @param other the string argument. 1327 * @param ooffset the starting offset of the subregion in the string 1328 * argument. 1329 * @param len the number of characters to compare. 1330 * @return {@code true} if the specified subregion of this string 1331 * matches the specified subregion of the string argument; 1332 * {@code false} otherwise. Whether the matching is exact 1333 * or case insensitive depends on the {@code ignoreCase} 1334 * argument. 1335 */ 1336 public boolean regionMatches(boolean ignoreCase, int toffset, 1337 String other, int ooffset, int len) { 1338 char ta[] = value; 1339 int to = toffset; 1340 char pa[] = other.value; 1341 int po = ooffset; 1342 // Note: toffset, ooffset, or len might be near -1>>>1. 1343 if ((ooffset < 0) || (toffset < 0) 1344 || (toffset > (long)value.length - len) 1345 || (ooffset > (long)other.value.length - len)) { 1346 return false; 1347 } 1348 while (len-- > 0) { 1349 char c1 = ta[to++]; 1350 char c2 = pa[po++]; 1351 if (c1 == c2) { 1352 continue; 1353 } 1354 if (ignoreCase) { 1355 // If characters don't match but case may be ignored, 1356 // try converting both characters to uppercase. 1357 // If the results match, then the comparison scan should 1358 // continue. 1359 char u1 = Character.toUpperCase(c1); 1360 char u2 = Character.toUpperCase(c2); 1361 if (u1 == u2) { 1362 continue; 1363 } 1364 // Unfortunately, conversion to uppercase does not work properly 1365 // for the Georgian alphabet, which has strange rules about case 1366 // conversion. So we need to make one last check before 1367 // exiting. 1368 if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) { 1369 continue; 1370 } 1371 } 1372 return false; 1373 } 1374 return true; 1375 } 1376 1377 /** 1378 * Tests if the substring of this string beginning at the 1379 * specified index starts with the specified prefix. 1380 * 1381 * @param prefix the prefix. 1382 * @param toffset where to begin looking in this string. 1383 * @return {@code true} if the character sequence represented by the 1384 * argument is a prefix of the substring of this object starting 1385 * at index {@code toffset}; {@code false} otherwise. 1386 * The result is {@code false} if {@code toffset} is 1387 * negative or greater than the length of this 1388 * {@code String} object; otherwise the result is the same 1389 * as the result of the expression 1390 * <pre> 1391 * this.substring(toffset).startsWith(prefix) 1392 * </pre> 1393 */ 1394 public boolean startsWith(String prefix, int toffset) { 1395 char ta[] = value; 1396 int to = toffset; 1397 char pa[] = prefix.value; 1398 int po = 0; 1399 int pc = prefix.value.length; 1400 // Note: toffset might be near -1>>>1. 1401 if ((toffset < 0) || (toffset > value.length - pc)) { 1402 return false; 1403 } 1404 while (--pc >= 0) { 1405 if (ta[to++] != pa[po++]) { 1406 return false; 1407 } 1408 } 1409 return true; 1410 } 1411 1412 /** 1413 * Tests if this string starts with the specified prefix. 1414 * 1415 * @param prefix the prefix. 1416 * @return {@code true} if the character sequence represented by the 1417 * argument is a prefix of the character sequence represented by 1418 * this string; {@code false} otherwise. 1419 * Note also that {@code true} will be returned if the 1420 * argument is an empty string or is equal to this 1421 * {@code String} object as determined by the 1422 * {@link #equals(Object)} method. 1423 * @since 1. 0 1424 */ 1425 public boolean startsWith(String prefix) { 1426 return startsWith(prefix, 0); 1427 } 1428 1429 /** 1430 * Tests if this string ends with the specified suffix. 1431 * 1432 * @param suffix the suffix. 1433 * @return {@code true} if the character sequence represented by the 1434 * argument is a suffix of the character sequence represented by 1435 * this object; {@code false} otherwise. Note that the 1436 * result will be {@code true} if the argument is the 1437 * empty string or is equal to this {@code String} object 1438 * as determined by the {@link #equals(Object)} method. 1439 */ 1440 public boolean endsWith(String suffix) { 1441 return startsWith(suffix, value.length - suffix.value.length); 1442 } 1443 1444 /** 1445 * Returns a hash code for this string. The hash code for a 1446 * {@code String} object is computed as 1447 * <blockquote><pre> 1448 * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] 1449 * </pre></blockquote> 1450 * using {@code int} arithmetic, where {@code s[i]} is the 1451 * <i>i</i>th character of the string, {@code n} is the length of 1452 * the string, and {@code ^} indicates exponentiation. 1453 * (The hash value of the empty string is zero.) 1454 * 1455 * @return a hash code value for this object. 1456 */ 1457 public int hashCode() { 1458 int h = hash; 1459 if (h == 0 && value.length > 0) { 1460 char val[] = value; 1461 1462 for (int i = 0; i < value.length; i++) { 1463 h = 31 * h + val[i]; 1464 } 1465 hash = h; 1466 } 1467 return h; 1468 } 1469 1470 /** 1471 * Returns the index within this string of the first occurrence of 1472 * the specified character. If a character with value 1473 * {@code ch} occurs in the character sequence represented by 1474 * this {@code String} object, then the index (in Unicode 1475 * code units) of the first such occurrence is returned. For 1476 * values of {@code ch} in the range from 0 to 0xFFFF 1477 * (inclusive), this is the smallest value <i>k</i> such that: 1478 * <blockquote><pre> 1479 * this.charAt(<i>k</i>) == ch 1480 * </pre></blockquote> 1481 * is true. For other values of {@code ch}, it is the 1482 * smallest value <i>k</i> such that: 1483 * <blockquote><pre> 1484 * this.codePointAt(<i>k</i>) == ch 1485 * </pre></blockquote> 1486 * is true. In either case, if no such character occurs in this 1487 * string, then {@code -1} is returned. 1488 * 1489 * @param ch a character (Unicode code point). 1490 * @return the index of the first occurrence of the character in the 1491 * character sequence represented by this object, or 1492 * {@code -1} if the character does not occur. 1493 */ 1494 public int indexOf(int ch) { 1495 return indexOf(ch, 0); 1496 } 1497 1498 /** 1499 * Returns the index within this string of the first occurrence of the 1500 * specified character, starting the search at the specified index. 1501 * <p> 1502 * If a character with value {@code ch} occurs in the 1503 * character sequence represented by this {@code String} 1504 * object at an index no smaller than {@code fromIndex}, then 1505 * the index of the first such occurrence is returned. For values 1506 * of {@code ch} in the range from 0 to 0xFFFF (inclusive), 1507 * this is the smallest value <i>k</i> such that: 1508 * <blockquote><pre> 1509 * (this.charAt(<i>k</i>) == ch) {@code &&} (<i>k</i> >= fromIndex) 1510 * </pre></blockquote> 1511 * is true. For other values of {@code ch}, it is the 1512 * smallest value <i>k</i> such that: 1513 * <blockquote><pre> 1514 * (this.codePointAt(<i>k</i>) == ch) {@code &&} (<i>k</i> >= fromIndex) 1515 * </pre></blockquote> 1516 * is true. In either case, if no such character occurs in this 1517 * string at or after position {@code fromIndex}, then 1518 * {@code -1} is returned. 1519 * 1520 * <p> 1521 * There is no restriction on the value of {@code fromIndex}. If it 1522 * is negative, it has the same effect as if it were zero: this entire 1523 * string may be searched. If it is greater than the length of this 1524 * string, it has the same effect as if it were equal to the length of 1525 * this string: {@code -1} is returned. 1526 * 1527 * <p>All indices are specified in {@code char} values 1528 * (Unicode code units). 1529 * 1530 * @param ch a character (Unicode code point). 1531 * @param fromIndex the index to start the search from. 1532 * @return the index of the first occurrence of the character in the 1533 * character sequence represented by this object that is greater 1534 * than or equal to {@code fromIndex}, or {@code -1} 1535 * if the character does not occur. 1536 */ 1537 public int indexOf(int ch, int fromIndex) { 1538 final int max = value.length; 1539 if (fromIndex < 0) { 1540 fromIndex = 0; 1541 } else if (fromIndex >= max) { 1542 // Note: fromIndex might be near -1>>>1. 1543 return -1; 1544 } 1545 1546 if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) { 1547 // handle most cases here (ch is a BMP code point or a 1548 // negative value (invalid code point)) 1549 final char[] value = this.value; 1550 for (int i = fromIndex; i < max; i++) { 1551 if (value[i] == ch) { 1552 return i; 1553 } 1554 } 1555 return -1; 1556 } else { 1557 return indexOfSupplementary(ch, fromIndex); 1558 } 1559 } 1560 1561 /** 1562 * Handles (rare) calls of indexOf with a supplementary character. 1563 */ 1564 private int indexOfSupplementary(int ch, int fromIndex) { 1565 if (Character.isValidCodePoint(ch)) { 1566 final char[] value = this.value; 1567 final char hi = Character.highSurrogate(ch); 1568 final char lo = Character.lowSurrogate(ch); 1569 final int max = value.length - 1; 1570 for (int i = fromIndex; i < max; i++) { 1571 if (value[i] == hi && value[i + 1] == lo) { 1572 return i; 1573 } 1574 } 1575 } 1576 return -1; 1577 } 1578 1579 /** 1580 * Returns the index within this string of the last occurrence of 1581 * the specified character. For values of {@code ch} in the 1582 * range from 0 to 0xFFFF (inclusive), the index (in Unicode code 1583 * units) returned is the largest value <i>k</i> such that: 1584 * <blockquote><pre> 1585 * this.charAt(<i>k</i>) == ch 1586 * </pre></blockquote> 1587 * is true. For other values of {@code ch}, it is the 1588 * largest value <i>k</i> such that: 1589 * <blockquote><pre> 1590 * this.codePointAt(<i>k</i>) == ch 1591 * </pre></blockquote> 1592 * is true. In either case, if no such character occurs in this 1593 * string, then {@code -1} is returned. The 1594 * {@code String} is searched backwards starting at the last 1595 * character. 1596 * 1597 * @param ch a character (Unicode code point). 1598 * @return the index of the last occurrence of the character in the 1599 * character sequence represented by this object, or 1600 * {@code -1} if the character does not occur. 1601 */ 1602 public int lastIndexOf(int ch) { 1603 return lastIndexOf(ch, value.length - 1); 1604 } 1605 1606 /** 1607 * Returns the index within this string of the last occurrence of 1608 * the specified character, searching backward starting at the 1609 * specified index. For values of {@code ch} in the range 1610 * from 0 to 0xFFFF (inclusive), the index returned is the largest 1611 * value <i>k</i> such that: 1612 * <blockquote><pre> 1613 * (this.charAt(<i>k</i>) == ch) {@code &&} (<i>k</i> <= fromIndex) 1614 * </pre></blockquote> 1615 * is true. For other values of {@code ch}, it is the 1616 * largest value <i>k</i> such that: 1617 * <blockquote><pre> 1618 * (this.codePointAt(<i>k</i>) == ch) {@code &&} (<i>k</i> <= fromIndex) 1619 * </pre></blockquote> 1620 * is true. In either case, if no such character occurs in this 1621 * string at or before position {@code fromIndex}, then 1622 * {@code -1} is returned. 1623 * 1624 * <p>All indices are specified in {@code char} values 1625 * (Unicode code units). 1626 * 1627 * @param ch a character (Unicode code point). 1628 * @param fromIndex the index to start the search from. There is no 1629 * restriction on the value of {@code fromIndex}. If it is 1630 * greater than or equal to the length of this string, it has 1631 * the same effect as if it were equal to one less than the 1632 * length of this string: this entire string may be searched. 1633 * If it is negative, it has the same effect as if it were -1: 1634 * -1 is returned. 1635 * @return the index of the last occurrence of the character in the 1636 * character sequence represented by this object that is less 1637 * than or equal to {@code fromIndex}, or {@code -1} 1638 * if the character does not occur before that point. 1639 */ 1640 public int lastIndexOf(int ch, int fromIndex) { 1641 if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) { 1642 // handle most cases here (ch is a BMP code point or a 1643 // negative value (invalid code point)) 1644 final char[] value = this.value; 1645 int i = Math.min(fromIndex, value.length - 1); 1646 for (; i >= 0; i--) { 1647 if (value[i] == ch) { 1648 return i; 1649 } 1650 } 1651 return -1; 1652 } else { 1653 return lastIndexOfSupplementary(ch, fromIndex); 1654 } 1655 } 1656 1657 /** 1658 * Handles (rare) calls of lastIndexOf with a supplementary character. 1659 */ 1660 private int lastIndexOfSupplementary(int ch, int fromIndex) { 1661 if (Character.isValidCodePoint(ch)) { 1662 final char[] value = this.value; 1663 char hi = Character.highSurrogate(ch); 1664 char lo = Character.lowSurrogate(ch); 1665 int i = Math.min(fromIndex, value.length - 2); 1666 for (; i >= 0; i--) { 1667 if (value[i] == hi && value[i + 1] == lo) { 1668 return i; 1669 } 1670 } 1671 } 1672 return -1; 1673 } 1674 1675 /** 1676 * Returns the index within this string of the first occurrence of the 1677 * specified substring. 1678 * 1679 * <p>The returned index is the smallest value <i>k</i> for which: 1680 * <blockquote><pre> 1681 * this.startsWith(str, <i>k</i>) 1682 * </pre></blockquote> 1683 * If no such value of <i>k</i> exists, then {@code -1} is returned. 1684 * 1685 * @param str the substring to search for. 1686 * @return the index of the first occurrence of the specified substring, 1687 * or {@code -1} if there is no such occurrence. 1688 */ 1689 public int indexOf(String str) { 1690 return indexOf(str, 0); 1691 } 1692 1693 /** 1694 * Returns the index within this string of the first occurrence of the 1695 * specified substring, starting at the specified index. 1696 * 1697 * <p>The returned index is the smallest value <i>k</i> for which: 1698 * <blockquote><pre> 1699 * <i>k</i> >= fromIndex {@code &&} this.startsWith(str, <i>k</i>) 1700 * </pre></blockquote> 1701 * If no such value of <i>k</i> exists, then {@code -1} is returned. 1702 * 1703 * @param str the substring to search for. 1704 * @param fromIndex the index from which to start the search. 1705 * @return the index of the first occurrence of the specified substring, 1706 * starting at the specified index, 1707 * or {@code -1} if there is no such occurrence. 1708 */ 1709 public int indexOf(String str, int fromIndex) { 1710 return indexOf(value, 0, value.length, 1711 str.value, 0, str.value.length, fromIndex); 1712 } 1713 1714 /** 1715 * Code shared by String and AbstractStringBuilder to do searches. The 1716 * source is the character array being searched, and the target 1717 * is the string being searched for. 1718 * 1719 * @param source the characters being searched. 1720 * @param sourceOffset offset of the source string. 1721 * @param sourceCount count of the source string. 1722 * @param target the characters being searched for. 1723 * @param fromIndex the index to begin searching from. 1724 */ 1725 static int indexOf(char[] source, int sourceOffset, int sourceCount, 1726 String target, int fromIndex) { 1727 return indexOf(source, sourceOffset, sourceCount, 1728 target.value, 0, target.value.length, 1729 fromIndex); 1730 } 1731 1732 /** 1733 * Code shared by String and StringBuffer to do searches. The 1734 * source is the character array being searched, and the target 1735 * is the string being searched for. 1736 * 1737 * @param source the characters being searched. 1738 * @param sourceOffset offset of the source string. 1739 * @param sourceCount count of the source string. 1740 * @param target the characters being searched for. 1741 * @param targetOffset offset of the target string. 1742 * @param targetCount count of the target string. 1743 * @param fromIndex the index to begin searching from. 1744 */ 1745 static int indexOf(char[] source, int sourceOffset, int sourceCount, 1746 char[] target, int targetOffset, int targetCount, 1747 int fromIndex) { 1748 if (fromIndex >= sourceCount) { 1749 return (targetCount == 0 ? sourceCount : -1); 1750 } 1751 if (fromIndex < 0) { 1752 fromIndex = 0; 1753 } 1754 if (targetCount == 0) { 1755 return fromIndex; 1756 } 1757 1758 char first = target[targetOffset]; 1759 int max = sourceOffset + (sourceCount - targetCount); 1760 1761 for (int i = sourceOffset + fromIndex; i <= max; i++) { 1762 /* Look for first character. */ 1763 if (source[i] != first) { 1764 while (++i <= max && source[i] != first); 1765 } 1766 1767 /* Found first character, now look at the rest of v2 */ 1768 if (i <= max) { 1769 int j = i + 1; 1770 int end = j + targetCount - 1; 1771 for (int k = targetOffset + 1; j < end && source[j] 1772 == target[k]; j++, k++); 1773 1774 if (j == end) { 1775 /* Found whole string. */ 1776 return i - sourceOffset; 1777 } 1778 } 1779 } 1780 return -1; 1781 } 1782 1783 /** 1784 * Returns the index within this string of the last occurrence of the 1785 * specified substring. The last occurrence of the empty string "" 1786 * is considered to occur at the index value {@code this.length()}. 1787 * 1788 * <p>The returned index is the largest value <i>k</i> for which: 1789 * <blockquote><pre> 1790 * this.startsWith(str, <i>k</i>) 1791 * </pre></blockquote> 1792 * If no such value of <i>k</i> exists, then {@code -1} is returned. 1793 * 1794 * @param str the substring to search for. 1795 * @return the index of the last occurrence of the specified substring, 1796 * or {@code -1} if there is no such occurrence. 1797 */ 1798 public int lastIndexOf(String str) { 1799 return lastIndexOf(str, value.length); 1800 } 1801 1802 /** 1803 * Returns the index within this string of the last occurrence of the 1804 * specified substring, searching backward starting at the specified index. 1805 * 1806 * <p>The returned index is the largest value <i>k</i> for which: 1807 * <blockquote><pre> 1808 * <i>k</i> {@code <=} fromIndex {@code &&} this.startsWith(str, <i>k</i>) 1809 * </pre></blockquote> 1810 * If no such value of <i>k</i> exists, then {@code -1} is returned. 1811 * 1812 * @param str the substring to search for. 1813 * @param fromIndex the index to start the search from. 1814 * @return the index of the last occurrence of the specified substring, 1815 * searching backward from the specified index, 1816 * or {@code -1} if there is no such occurrence. 1817 */ 1818 public int lastIndexOf(String str, int fromIndex) { 1819 return lastIndexOf(value, 0, value.length, 1820 str.value, 0, str.value.length, fromIndex); 1821 } 1822 1823 /** 1824 * Code shared by String and AbstractStringBuilder to do searches. The 1825 * source is the character array being searched, and the target 1826 * is the string being searched for. 1827 * 1828 * @param source the characters being searched. 1829 * @param sourceOffset offset of the source string. 1830 * @param sourceCount count of the source string. 1831 * @param target the characters being searched for. 1832 * @param fromIndex the index to begin searching from. 1833 */ 1834 static int lastIndexOf(char[] source, int sourceOffset, int sourceCount, 1835 String target, int fromIndex) { 1836 return lastIndexOf(source, sourceOffset, sourceCount, 1837 target.value, 0, target.value.length, 1838 fromIndex); 1839 } 1840 1841 /** 1842 * Code shared by String and StringBuffer to do searches. The 1843 * source is the character array being searched, and the target 1844 * is the string being searched for. 1845 * 1846 * @param source the characters being searched. 1847 * @param sourceOffset offset of the source string. 1848 * @param sourceCount count of the source string. 1849 * @param target the characters being searched for. 1850 * @param targetOffset offset of the target string. 1851 * @param targetCount count of the target string. 1852 * @param fromIndex the index to begin searching from. 1853 */ 1854 static int lastIndexOf(char[] source, int sourceOffset, int sourceCount, 1855 char[] target, int targetOffset, int targetCount, 1856 int fromIndex) { 1857 /* 1858 * Check arguments; return immediately where possible. For 1859 * consistency, don't check for null str. 1860 */ 1861 int rightIndex = sourceCount - targetCount; 1862 if (fromIndex < 0) { 1863 return -1; 1864 } 1865 if (fromIndex > rightIndex) { 1866 fromIndex = rightIndex; 1867 } 1868 /* Empty string always matches. */ 1869 if (targetCount == 0) { 1870 return fromIndex; 1871 } 1872 1873 int strLastIndex = targetOffset + targetCount - 1; 1874 char strLastChar = target[strLastIndex]; 1875 int min = sourceOffset + targetCount - 1; 1876 int i = min + fromIndex; 1877 1878 startSearchForLastChar: 1879 while (true) { 1880 while (i >= min && source[i] != strLastChar) { 1881 i--; 1882 } 1883 if (i < min) { 1884 return -1; 1885 } 1886 int j = i - 1; 1887 int start = j - (targetCount - 1); 1888 int k = strLastIndex - 1; 1889 1890 while (j > start) { 1891 if (source[j--] != target[k--]) { 1892 i--; 1893 continue startSearchForLastChar; 1894 } 1895 } 1896 return start - sourceOffset + 1; 1897 } 1898 } 1899 1900 /** 1901 * Returns a new string that is a substring of this string. The 1902 * substring begins with the character at the specified index and 1903 * extends to the end of this string. <p> 1904 * Examples: 1905 * <blockquote><pre> 1906 * "unhappy".substring(2) returns "happy" 1907 * "Harbison".substring(3) returns "bison" 1908 * "emptiness".substring(9) returns "" (an empty string) 1909 * </pre></blockquote> 1910 * 1911 * @param beginIndex the beginning index, inclusive. 1912 * @return the specified substring. 1913 * @exception IndexOutOfBoundsException if 1914 * {@code beginIndex} is negative or larger than the 1915 * length of this {@code String} object. 1916 */ 1917 public String substring(int beginIndex) { 1918 if (beginIndex < 0) { 1919 throw new StringIndexOutOfBoundsException(beginIndex); 1920 } 1921 int subLen = value.length - beginIndex; 1922 if (subLen < 0) { 1923 throw new StringIndexOutOfBoundsException(subLen); 1924 } 1925 return (beginIndex == 0) ? this : new String(value, beginIndex, subLen); 1926 } 1927 1928 /** 1929 * Returns a new string that is a substring of this string. The 1930 * substring begins at the specified {@code beginIndex} and 1931 * extends to the character at index {@code endIndex - 1}. 1932 * Thus the length of the substring is {@code endIndex-beginIndex}. 1933 * <p> 1934 * Examples: 1935 * <blockquote><pre> 1936 * "hamburger".substring(4, 8) returns "urge" 1937 * "smiles".substring(1, 5) returns "mile" 1938 * </pre></blockquote> 1939 * 1940 * @param beginIndex the beginning index, inclusive. 1941 * @param endIndex the ending index, exclusive. 1942 * @return the specified substring. 1943 * @exception IndexOutOfBoundsException if the 1944 * {@code beginIndex} is negative, or 1945 * {@code endIndex} is larger than the length of 1946 * this {@code String} object, or 1947 * {@code beginIndex} is larger than 1948 * {@code endIndex}. 1949 */ 1950 public String substring(int beginIndex, int endIndex) { 1951 if (beginIndex < 0) { 1952 throw new StringIndexOutOfBoundsException(beginIndex); 1953 } 1954 if (endIndex > value.length) { 1955 throw new StringIndexOutOfBoundsException(endIndex); 1956 } 1957 int subLen = endIndex - beginIndex; 1958 if (subLen < 0) { 1959 throw new StringIndexOutOfBoundsException(subLen); 1960 } 1961 return ((beginIndex == 0) && (endIndex == value.length)) ? this 1962 : new String(value, beginIndex, subLen); 1963 } 1964 1965 /** 1966 * Returns a new character sequence that is a subsequence of this sequence. 1967 * 1968 * <p> An invocation of this method of the form 1969 * 1970 * <blockquote><pre> 1971 * str.subSequence(begin, end)</pre></blockquote> 1972 * 1973 * behaves in exactly the same way as the invocation 1974 * 1975 * <blockquote><pre> 1976 * str.substring(begin, end)</pre></blockquote> 1977 * 1978 * This method is defined so that the {@code String} class can implement 1979 * the {@link CharSequence} interface. 1980 * 1981 * @param beginIndex the begin index, inclusive. 1982 * @param endIndex the end index, exclusive. 1983 * @return the specified subsequence. 1984 * 1985 * @throws IndexOutOfBoundsException 1986 * if {@code beginIndex} or {@code endIndex} is negative, 1987 * if {@code endIndex} is greater than {@code length()}, 1988 * or if {@code beginIndex} is greater than {@code endIndex} 1989 * 1990 * @since 1.4 1991 * @spec JSR-51 1992 */ 1993 public CharSequence subSequence(int beginIndex, int endIndex) { 1994 return this.substring(beginIndex, endIndex); 1995 } 1996 1997 /** 1998 * Concatenates the specified string to the end of this string. 1999 * <p> 2000 * If the length of the argument string is {@code 0}, then this 2001 * {@code String} object is returned. Otherwise, a new 2002 * {@code String} object is created, representing a character 2003 * sequence that is the concatenation of the character sequence 2004 * represented by this {@code String} object and the character 2005 * sequence represented by the argument string.<p> 2006 * Examples: 2007 * <blockquote><pre> 2008 * "cares".concat("s") returns "caress" 2009 * "to".concat("get").concat("her") returns "together" 2010 * </pre></blockquote> 2011 * 2012 * @param str the {@code String} that is concatenated to the end 2013 * of this {@code String}. 2014 * @return a string that represents the concatenation of this object's 2015 * characters followed by the string argument's characters. 2016 */ 2017 public String concat(String str) { 2018 int otherLen = str.length(); 2019 if (otherLen == 0) { 2020 return this; 2021 } 2022 int len = value.length; 2023 char buf[] = Arrays.copyOf(value, len + otherLen); 2024 str.getChars(buf, len); 2025 return new String(buf, true); 2026 } 2027 2028 /** 2029 * Returns a new string resulting from replacing all occurrences of 2030 * {@code oldChar} in this string with {@code newChar}. 2031 * <p> 2032 * If the character {@code oldChar} does not occur in the 2033 * character sequence represented by this {@code String} object, 2034 * then a reference to this {@code String} object is returned. 2035 * Otherwise, a new {@code String} object is created that 2036 * represents a character sequence identical to the character sequence 2037 * represented by this {@code String} object, except that every 2038 * occurrence of {@code oldChar} is replaced by an occurrence 2039 * of {@code newChar}. 2040 * <p> 2041 * Examples: 2042 * <blockquote><pre> 2043 * "mesquite in your cellar".replace('e', 'o') 2044 * returns "mosquito in your collar" 2045 * "the war of baronets".replace('r', 'y') 2046 * returns "the way of bayonets" 2047 * "sparring with a purple porpoise".replace('p', 't') 2048 * returns "starring with a turtle tortoise" 2049 * "JonL".replace('q', 'x') returns "JonL" (no change) 2050 * </pre></blockquote> 2051 * 2052 * @param oldChar the old character. 2053 * @param newChar the new character. 2054 * @return a string derived from this string by replacing every 2055 * occurrence of {@code oldChar} with {@code newChar}. 2056 */ 2057 public String replace(char oldChar, char newChar) { 2058 if (oldChar != newChar) { 2059 int len = value.length; 2060 int i = -1; 2061 char[] val = value; /* avoid getfield opcode */ 2062 2063 while (++i < len) { 2064 if (val[i] == oldChar) { 2065 break; 2066 } 2067 } 2068 if (i < len) { 2069 char buf[] = new char[len]; 2070 for (int j = 0; j < i; j++) { 2071 buf[j] = val[j]; 2072 } 2073 while (i < len) { 2074 char c = val[i]; 2075 buf[i] = (c == oldChar) ? newChar : c; 2076 i++; 2077 } 2078 return new String(buf, true); 2079 } 2080 } 2081 return this; 2082 } 2083 2084 /** 2085 * Tells whether or not this string matches the given <a 2086 * href="../util/regex/Pattern.html#sum">regular expression</a>. 2087 * 2088 * <p> An invocation of this method of the form 2089 * <i>str</i>{@code .matches(}<i>regex</i>{@code )} yields exactly the 2090 * same result as the expression 2091 * 2092 * <blockquote> 2093 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#matches(String,CharSequence) 2094 * matches(<i>regex</i>, <i>str</i>)} 2095 * </blockquote> 2096 * 2097 * @param regex 2098 * the regular expression to which this string is to be matched 2099 * 2100 * @return {@code true} if, and only if, this string matches the 2101 * given regular expression 2102 * 2103 * @throws PatternSyntaxException 2104 * if the regular expression's syntax is invalid 2105 * 2106 * @see java.util.regex.Pattern 2107 * 2108 * @since 1.4 2109 * @spec JSR-51 2110 */ 2111 public boolean matches(String regex) { 2112 return Pattern.matches(regex, this); 2113 } 2114 2115 /** 2116 * Returns true if and only if this string contains the specified 2117 * sequence of char values. 2118 * 2119 * @param s the sequence to search for 2120 * @return true if this string contains {@code s}, false otherwise 2121 * @since 1.5 2122 */ 2123 public boolean contains(CharSequence s) { 2124 return indexOf(s.toString()) > -1; 2125 } 2126 2127 /** 2128 * Replaces the first substring of this string that matches the given <a 2129 * href="../util/regex/Pattern.html#sum">regular expression</a> with the 2130 * given replacement. 2131 * 2132 * <p> An invocation of this method of the form 2133 * <i>str</i>{@code .replaceFirst(}<i>regex</i>{@code ,} <i>repl</i>{@code )} 2134 * yields exactly the same result as the expression 2135 * 2136 * <blockquote> 2137 * <code> 2138 * {@link java.util.regex.Pattern}.{@link 2139 * java.util.regex.Pattern#compile compile}(<i>regex</i>).{@link 2140 * java.util.regex.Pattern#matcher(java.lang.CharSequence) matcher}(<i>str</i>).{@link 2141 * java.util.regex.Matcher#replaceFirst replaceFirst}(<i>repl</i>) 2142 * </code> 2143 * </blockquote> 2144 * 2145 *<p> 2146 * Note that backslashes ({@code \}) and dollar signs ({@code $}) in the 2147 * replacement string may cause the results to be different than if it were 2148 * being treated as a literal replacement string; see 2149 * {@link java.util.regex.Matcher#replaceFirst}. 2150 * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special 2151 * meaning of these characters, if desired. 2152 * 2153 * @param regex 2154 * the regular expression to which this string is to be matched 2155 * @param replacement 2156 * the string to be substituted for the first match 2157 * 2158 * @return The resulting {@code String} 2159 * 2160 * @throws PatternSyntaxException 2161 * if the regular expression's syntax is invalid 2162 * 2163 * @see java.util.regex.Pattern 2164 * 2165 * @since 1.4 2166 * @spec JSR-51 2167 */ 2168 public String replaceFirst(String regex, String replacement) { 2169 return Pattern.compile(regex).matcher(this).replaceFirst(replacement); 2170 } 2171 2172 /** 2173 * Replaces each substring of this string that matches the given <a 2174 * href="../util/regex/Pattern.html#sum">regular expression</a> with the 2175 * given replacement. 2176 * 2177 * <p> An invocation of this method of the form 2178 * <i>str</i>{@code .replaceAll(}<i>regex</i>{@code ,} <i>repl</i>{@code )} 2179 * yields exactly the same result as the expression 2180 * 2181 * <blockquote> 2182 * <code> 2183 * {@link java.util.regex.Pattern}.{@link 2184 * java.util.regex.Pattern#compile compile}(<i>regex</i>).{@link 2185 * java.util.regex.Pattern#matcher(java.lang.CharSequence) matcher}(<i>str</i>).{@link 2186 * java.util.regex.Matcher#replaceAll replaceAll}(<i>repl</i>) 2187 * </code> 2188 * </blockquote> 2189 * 2190 *<p> 2191 * Note that backslashes ({@code \}) and dollar signs ({@code $}) in the 2192 * replacement string may cause the results to be different than if it were 2193 * being treated as a literal replacement string; see 2194 * {@link java.util.regex.Matcher#replaceAll Matcher.replaceAll}. 2195 * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special 2196 * meaning of these characters, if desired. 2197 * 2198 * @param regex 2199 * the regular expression to which this string is to be matched 2200 * @param replacement 2201 * the string to be substituted for each match 2202 * 2203 * @return The resulting {@code String} 2204 * 2205 * @throws PatternSyntaxException 2206 * if the regular expression's syntax is invalid 2207 * 2208 * @see java.util.regex.Pattern 2209 * 2210 * @since 1.4 2211 * @spec JSR-51 2212 */ 2213 public String replaceAll(String regex, String replacement) { 2214 return Pattern.compile(regex).matcher(this).replaceAll(replacement); 2215 } 2216 2217 /** 2218 * Replaces each substring of this string that matches the literal target 2219 * sequence with the specified literal replacement sequence. The 2220 * replacement proceeds from the beginning of the string to the end, for 2221 * example, replacing "aa" with "b" in the string "aaa" will result in 2222 * "ba" rather than "ab". 2223 * 2224 * @param target The sequence of char values to be replaced 2225 * @param replacement The replacement sequence of char values 2226 * @return The resulting string 2227 * @since 1.5 2228 */ 2229 public String replace(CharSequence target, CharSequence replacement) { 2230 return Pattern.compile(target.toString(), Pattern.LITERAL).matcher( 2231 this).replaceAll(Matcher.quoteReplacement(replacement.toString())); 2232 } 2233 2234 /** 2235 * Splits this string around matches of the given 2236 * <a href="../util/regex/Pattern.html#sum">regular expression</a>. 2237 * 2238 * <p> The array returned by this method contains each substring of this 2239 * string that is terminated by another substring that matches the given 2240 * expression or is terminated by the end of the string. The substrings in 2241 * the array are in the order in which they occur in this string. If the 2242 * expression does not match any part of the input then the resulting array 2243 * has just one element, namely this string. 2244 * 2245 * <p> The {@code limit} parameter controls the number of times the 2246 * pattern is applied and therefore affects the length of the resulting 2247 * array. If the limit <i>n</i> is greater than zero then the pattern 2248 * will be applied at most <i>n</i> - 1 times, the array's 2249 * length will be no greater than <i>n</i>, and the array's last entry 2250 * will contain all input beyond the last matched delimiter. If <i>n</i> 2251 * is non-positive then the pattern will be applied as many times as 2252 * possible and the array can have any length. If <i>n</i> is zero then 2253 * the pattern will be applied as many times as possible, the array can 2254 * have any length, and trailing empty strings will be discarded. 2255 * 2256 * <p> The string {@code "boo:and:foo"}, for example, yields the 2257 * following results with these parameters: 2258 * 2259 * <blockquote><table cellpadding=1 cellspacing=0 summary="Split example showing regex, limit, and result"> 2260 * <tr> 2261 * <th>Regex</th> 2262 * <th>Limit</th> 2263 * <th>Result</th> 2264 * </tr> 2265 * <tr><td align=center>:</td> 2266 * <td align=center>2</td> 2267 * <td>{@code { "boo", "and:foo" }}</td></tr> 2268 * <tr><td align=center>:</td> 2269 * <td align=center>5</td> 2270 * <td>{@code { "boo", "and", "foo" }}</td></tr> 2271 * <tr><td align=center>:</td> 2272 * <td align=center>-2</td> 2273 * <td>{@code { "boo", "and", "foo" }}</td></tr> 2274 * <tr><td align=center>o</td> 2275 * <td align=center>5</td> 2276 * <td>{@code { "b", "", ":and:f", "", "" }}</td></tr> 2277 * <tr><td align=center>o</td> 2278 * <td align=center>-2</td> 2279 * <td>{@code { "b", "", ":and:f", "", "" }}</td></tr> 2280 * <tr><td align=center>o</td> 2281 * <td align=center>0</td> 2282 * <td>{@code { "b", "", ":and:f" }}</td></tr> 2283 * </table></blockquote> 2284 * 2285 * <p> An invocation of this method of the form 2286 * <i>str.</i>{@code split(}<i>regex</i>{@code ,} <i>n</i>{@code )} 2287 * yields the same result as the expression 2288 * 2289 * <blockquote> 2290 * <code> 2291 * {@link java.util.regex.Pattern}.{@link 2292 * java.util.regex.Pattern#compile compile}(<i>regex</i>).{@link 2293 * java.util.regex.Pattern#split(java.lang.CharSequence,int) split}(<i>str</i>, <i>n</i>) 2294 * </code> 2295 * </blockquote> 2296 * 2297 * 2298 * @param regex 2299 * the delimiting regular expression 2300 * 2301 * @param limit 2302 * the result threshold, as described above 2303 * 2304 * @return the array of strings computed by splitting this string 2305 * around matches of the given regular expression 2306 * 2307 * @throws PatternSyntaxException 2308 * if the regular expression's syntax is invalid 2309 * 2310 * @see java.util.regex.Pattern 2311 * 2312 * @since 1.4 2313 * @spec JSR-51 2314 */ 2315 public String[] split(String regex, int limit) { 2316 /* fastpath if the regex is a 2317 (1)one-char String and this character is not one of the 2318 RegEx's meta characters ".$|()[{^?*+\\", or 2319 (2)two-char String and the first char is the backslash and 2320 the second is not the ascii digit or ascii letter. 2321 */ 2322 char ch = 0; 2323 if (((regex.value.length == 1 && 2324 ".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) || 2325 (regex.length() == 2 && 2326 regex.charAt(0) == '\\' && 2327 (((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 && 2328 ((ch-'a')|('z'-ch)) < 0 && 2329 ((ch-'A')|('Z'-ch)) < 0)) && 2330 (ch < Character.MIN_HIGH_SURROGATE || 2331 ch > Character.MAX_LOW_SURROGATE)) 2332 { 2333 int off = 0; 2334 int next = 0; 2335 boolean limited = limit > 0; 2336 ArrayList<String> list = new ArrayList<>(); 2337 while ((next = indexOf(ch, off)) != -1) { 2338 if (!limited || list.size() < limit - 1) { 2339 list.add(substring(off, next)); 2340 off = next + 1; 2341 } else { // last one 2342 //assert (list.size() == limit - 1); 2343 list.add(substring(off, value.length)); 2344 off = value.length; 2345 break; 2346 } 2347 } 2348 // If no match was found, return this 2349 if (off == 0) 2350 return new String[]{this}; 2351 2352 // Add remaining segment 2353 if (!limited || list.size() < limit) 2354 list.add(substring(off, value.length)); 2355 2356 // Construct result 2357 int resultSize = list.size(); 2358 if (limit == 0) { 2359 while (resultSize > 0 && list.get(resultSize - 1).length() == 0) { 2360 resultSize--; 2361 } 2362 } 2363 String[] result = new String[resultSize]; 2364 return list.subList(0, resultSize).toArray(result); 2365 } 2366 return Pattern.compile(regex).split(this, limit); 2367 } 2368 2369 /** 2370 * Splits this string around matches of the given <a 2371 * href="../util/regex/Pattern.html#sum">regular expression</a>. 2372 * 2373 * <p> This method works as if by invoking the two-argument {@link 2374 * #split(String, int) split} method with the given expression and a limit 2375 * argument of zero. Trailing empty strings are therefore not included in 2376 * the resulting array. 2377 * 2378 * <p> The string {@code "boo:and:foo"}, for example, yields the following 2379 * results with these expressions: 2380 * 2381 * <blockquote><table cellpadding=1 cellspacing=0 summary="Split examples showing regex and result"> 2382 * <tr> 2383 * <th>Regex</th> 2384 * <th>Result</th> 2385 * </tr> 2386 * <tr><td align=center>:</td> 2387 * <td>{@code { "boo", "and", "foo" }}</td></tr> 2388 * <tr><td align=center>o</td> 2389 * <td>{@code { "b", "", ":and:f" }}</td></tr> 2390 * </table></blockquote> 2391 * 2392 * 2393 * @param regex 2394 * the delimiting regular expression 2395 * 2396 * @return the array of strings computed by splitting this string 2397 * around matches of the given regular expression 2398 * 2399 * @throws PatternSyntaxException 2400 * if the regular expression's syntax is invalid 2401 * 2402 * @see java.util.regex.Pattern 2403 * 2404 * @since 1.4 2405 * @spec JSR-51 2406 */ 2407 public String[] split(String regex) { 2408 return split(regex, 0); 2409 } 2410 2411 /** 2412 * Returns a new String composed of copies of the 2413 * {@code CharSequence elements} joined together with a copy of 2414 * the specified {@code delimiter}. 2415 * 2416 * <blockquote>For example, 2417 * <pre>{@code 2418 * String message = String.join("-", "Java", "is", "cool"); 2419 * // message returned is: "Java-is-cool" 2420 * }</pre></blockquote> 2421 * 2422 * Note that if an element is null, then {@code "null"} is added. 2423 * 2424 * @param delimiter the delimiter that separates each element 2425 * @param elements the elements to join together. 2426 * 2427 * @return a new {@code String} that is composed of the {@code elements} 2428 * separated by the {@code delimiter} 2429 * 2430 * @throws NullPointerException If {@code delimiter} or {@code elements} 2431 * is {@code null} 2432 * 2433 * @see java.util.StringJoiner 2434 * @since 1.8 2435 */ 2436 public static String join(CharSequence delimiter, CharSequence... elements) { 2437 Objects.requireNonNull(delimiter); 2438 Objects.requireNonNull(elements); 2439 // Number of elements not likely worth Arrays.stream overhead. 2440 StringJoiner joiner = new StringJoiner(delimiter); 2441 for (CharSequence cs: elements) { 2442 joiner.add(cs); 2443 } 2444 return joiner.toString(); 2445 } 2446 2447 /** 2448 * Returns a new {@code String} composed of copies of the 2449 * {@code CharSequence elements} joined together with a copy of the 2450 * specified {@code delimiter}. 2451 * 2452 * <blockquote>For example, 2453 * <pre>{@code 2454 * List<String> strings = new LinkedList<>(); 2455 * strings.add("Java");strings.add("is"); 2456 * strings.add("cool"); 2457 * String message = String.join(" ", strings); 2458 * //message returned is: "Java is cool" 2459 * 2460 * Set<String> strings = new HashSet<>(); 2461 * Strings.add("Java"); strings.add("is"); 2462 * strings.add("very"); strings.add("cool"); 2463 * String message = String.join("-", strings); 2464 * //message returned is: "Java-is-very-cool" 2465 * }</pre></blockquote> 2466 * 2467 * Note that if an individual element is {@code null}, then {@code "null"} is added. 2468 * 2469 * @param delimiter a sequence of characters that is used to separate each 2470 * of the {@code elements} in the resulting {@code String} 2471 * @param elements an {@code Iterable} that will have its {@code elements} 2472 * joined together. 2473 * 2474 * @return a new {@code String} that is composed from the {@code elements} 2475 * argument 2476 * 2477 * @throws NullPointerException If {@code delimiter} or {@code elements} 2478 * is {@code null} 2479 * 2480 * @see #join(CharSequence,CharSequence...) 2481 * @see java.util.StringJoiner 2482 * @since 1.8 2483 */ 2484 public static String join(CharSequence delimiter, 2485 Iterable<? extends CharSequence> elements) { 2486 Objects.requireNonNull(delimiter); 2487 Objects.requireNonNull(elements); 2488 StringJoiner joiner = new StringJoiner(delimiter); 2489 for (CharSequence cs: elements) { 2490 joiner.add(cs); 2491 } 2492 return joiner.toString(); 2493 } 2494 2495 /** 2496 * Converts all of the characters in this {@code String} to lower 2497 * case using the rules of the given {@code Locale}. Case mapping is based 2498 * on the Unicode Standard version specified by the {@link java.lang.Character Character} 2499 * class. Since case mappings are not always 1:1 char mappings, the resulting 2500 * {@code String} may be a different length than the original {@code String}. 2501 * <p> 2502 * Examples of lowercase mappings are in the following table: 2503 * <table border="1" summary="Lowercase mapping examples showing language code of locale, upper case, lower case, and description"> 2504 * <tr> 2505 * <th>Language Code of Locale</th> 2506 * <th>Upper Case</th> 2507 * <th>Lower Case</th> 2508 * <th>Description</th> 2509 * </tr> 2510 * <tr> 2511 * <td>tr (Turkish)</td> 2512 * <td>\u0130</td> 2513 * <td>\u0069</td> 2514 * <td>capital letter I with dot above -> small letter i</td> 2515 * </tr> 2516 * <tr> 2517 * <td>tr (Turkish)</td> 2518 * <td>\u0049</td> 2519 * <td>\u0131</td> 2520 * <td>capital letter I -> small letter dotless i </td> 2521 * </tr> 2522 * <tr> 2523 * <td>(all)</td> 2524 * <td>French Fries</td> 2525 * <td>french fries</td> 2526 * <td>lowercased all chars in String</td> 2527 * </tr> 2528 * <tr> 2529 * <td>(all)</td> 2530 * <td><img src="doc-files/capiota.gif" alt="capiota"><img src="doc-files/capchi.gif" alt="capchi"> 2531 * <img src="doc-files/captheta.gif" alt="captheta"><img src="doc-files/capupsil.gif" alt="capupsil"> 2532 * <img src="doc-files/capsigma.gif" alt="capsigma"></td> 2533 * <td><img src="doc-files/iota.gif" alt="iota"><img src="doc-files/chi.gif" alt="chi"> 2534 * <img src="doc-files/theta.gif" alt="theta"><img src="doc-files/upsilon.gif" alt="upsilon"> 2535 * <img src="doc-files/sigma1.gif" alt="sigma"></td> 2536 * <td>lowercased all chars in String</td> 2537 * </tr> 2538 * </table> 2539 * 2540 * @param locale use the case transformation rules for this locale 2541 * @return the {@code String}, converted to lowercase. 2542 * @see java.lang.String#toLowerCase() 2543 * @see java.lang.String#toUpperCase() 2544 * @see java.lang.String#toUpperCase(Locale) 2545 * @since 1.1 2546 */ 2547 public String toLowerCase(Locale locale) { 2548 if (locale == null) { 2549 throw new NullPointerException(); 2550 } 2551 2552 int firstUpper; 2553 final int len = value.length; 2554 2555 /* Now check if there are any characters that need to be changed. */ 2556 scan: { 2557 for (firstUpper = 0 ; firstUpper < len; ) { 2558 char c = value[firstUpper]; 2559 if ((c >= Character.MIN_HIGH_SURROGATE) 2560 && (c <= Character.MAX_HIGH_SURROGATE)) { 2561 int supplChar = codePointAt(firstUpper); 2562 if (supplChar != Character.toLowerCase(supplChar)) { 2563 break scan; 2564 } 2565 firstUpper += Character.charCount(supplChar); 2566 } else { 2567 if (c != Character.toLowerCase(c)) { 2568 break scan; 2569 } 2570 firstUpper++; 2571 } 2572 } 2573 return this; 2574 } 2575 2576 char[] result = new char[len]; 2577 int resultOffset = 0; /* result may grow, so i+resultOffset 2578 * is the write location in result */ 2579 2580 /* Just copy the first few lowerCase characters. */ 2581 System.arraycopy(value, 0, result, 0, firstUpper); 2582 2583 String lang = locale.getLanguage(); 2584 boolean localeDependent = 2585 (lang == "tr" || lang == "az" || lang == "lt"); 2586 char[] lowerCharArray; 2587 int lowerChar; 2588 int srcChar; 2589 int srcCount; 2590 for (int i = firstUpper; i < len; i += srcCount) { 2591 srcChar = (int)value[i]; 2592 if ((char)srcChar >= Character.MIN_HIGH_SURROGATE 2593 && (char)srcChar <= Character.MAX_HIGH_SURROGATE) { 2594 srcChar = codePointAt(i); 2595 srcCount = Character.charCount(srcChar); 2596 } else { 2597 srcCount = 1; 2598 } 2599 if (localeDependent || srcChar == '\u03A3') { // GREEK CAPITAL LETTER SIGMA 2600 lowerChar = ConditionalSpecialCasing.toLowerCaseEx(this, i, locale); 2601 } else if (srcChar == '\u0130') { // LATIN CAPITAL LETTER I DOT 2602 lowerChar = Character.ERROR; 2603 } else { 2604 lowerChar = Character.toLowerCase(srcChar); 2605 } 2606 if ((lowerChar == Character.ERROR) 2607 || (lowerChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) { 2608 if (lowerChar == Character.ERROR) { 2609 if (!localeDependent && srcChar == '\u0130') { 2610 lowerCharArray = 2611 ConditionalSpecialCasing.toLowerCaseCharArray(this, i, Locale.ENGLISH); 2612 } else { 2613 lowerCharArray = 2614 ConditionalSpecialCasing.toLowerCaseCharArray(this, i, locale); 2615 } 2616 } else if (srcCount == 2) { 2617 resultOffset += Character.toChars(lowerChar, result, i + resultOffset) - srcCount; 2618 continue; 2619 } else { 2620 lowerCharArray = Character.toChars(lowerChar); 2621 } 2622 2623 /* Grow result if needed */ 2624 int mapLen = lowerCharArray.length; 2625 if (mapLen > srcCount) { 2626 char[] result2 = new char[result.length + mapLen - srcCount]; 2627 System.arraycopy(result, 0, result2, 0, i + resultOffset); 2628 result = result2; 2629 } 2630 for (int x = 0; x < mapLen; ++x) { 2631 result[i + resultOffset + x] = lowerCharArray[x]; 2632 } 2633 resultOffset += (mapLen - srcCount); 2634 } else { 2635 result[i + resultOffset] = (char)lowerChar; 2636 } 2637 } 2638 return new String(result, 0, len + resultOffset); 2639 } 2640 2641 /** 2642 * Converts all of the characters in this {@code String} to lower 2643 * case using the rules of the default locale. This is equivalent to calling 2644 * {@code toLowerCase(Locale.getDefault())}. 2645 * <p> 2646 * <b>Note:</b> This method is locale sensitive, and may produce unexpected 2647 * results if used for strings that are intended to be interpreted locale 2648 * independently. 2649 * Examples are programming language identifiers, protocol keys, and HTML 2650 * tags. 2651 * For instance, {@code "TITLE".toLowerCase()} in a Turkish locale 2652 * returns {@code "t\u005Cu0131tle"}, where '\u005Cu0131' is the 2653 * LATIN SMALL LETTER DOTLESS I character. 2654 * To obtain correct results for locale insensitive strings, use 2655 * {@code toLowerCase(Locale.ENGLISH)}. 2656 * <p> 2657 * @return the {@code String}, converted to lowercase. 2658 * @see java.lang.String#toLowerCase(Locale) 2659 */ 2660 public String toLowerCase() { 2661 return toLowerCase(Locale.getDefault()); 2662 } 2663 2664 /** 2665 * Converts all of the characters in this {@code String} to upper 2666 * case using the rules of the given {@code Locale}. Case mapping is based 2667 * on the Unicode Standard version specified by the {@link java.lang.Character Character} 2668 * class. Since case mappings are not always 1:1 char mappings, the resulting 2669 * {@code String} may be a different length than the original {@code String}. 2670 * <p> 2671 * Examples of locale-sensitive and 1:M case mappings are in the following table. 2672 * <p> 2673 * <table border="1" summary="Examples of locale-sensitive and 1:M case mappings. Shows Language code of locale, lower case, upper case, and description."> 2674 * <tr> 2675 * <th>Language Code of Locale</th> 2676 * <th>Lower Case</th> 2677 * <th>Upper Case</th> 2678 * <th>Description</th> 2679 * </tr> 2680 * <tr> 2681 * <td>tr (Turkish)</td> 2682 * <td>\u0069</td> 2683 * <td>\u0130</td> 2684 * <td>small letter i -> capital letter I with dot above</td> 2685 * </tr> 2686 * <tr> 2687 * <td>tr (Turkish)</td> 2688 * <td>\u0131</td> 2689 * <td>\u0049</td> 2690 * <td>small letter dotless i -> capital letter I</td> 2691 * </tr> 2692 * <tr> 2693 * <td>(all)</td> 2694 * <td>\u00df</td> 2695 * <td>\u0053 \u0053</td> 2696 * <td>small letter sharp s -> two letters: SS</td> 2697 * </tr> 2698 * <tr> 2699 * <td>(all)</td> 2700 * <td>Fahrvergnügen</td> 2701 * <td>FAHRVERGNÜGEN</td> 2702 * <td></td> 2703 * </tr> 2704 * </table> 2705 * @param locale use the case transformation rules for this locale 2706 * @return the {@code String}, converted to uppercase. 2707 * @see java.lang.String#toUpperCase() 2708 * @see java.lang.String#toLowerCase() 2709 * @see java.lang.String#toLowerCase(Locale) 2710 * @since 1.1 2711 */ 2712 public String toUpperCase(Locale locale) { 2713 if (locale == null) { 2714 throw new NullPointerException(); 2715 } 2716 2717 int firstLower; 2718 final int len = value.length; 2719 2720 /* Now check if there are any characters that need to be changed. */ 2721 scan: { 2722 for (firstLower = 0 ; firstLower < len; ) { 2723 int c = (int)value[firstLower]; 2724 int srcCount; 2725 if ((c >= Character.MIN_HIGH_SURROGATE) 2726 && (c <= Character.MAX_HIGH_SURROGATE)) { 2727 c = codePointAt(firstLower); 2728 srcCount = Character.charCount(c); 2729 } else { 2730 srcCount = 1; 2731 } 2732 int upperCaseChar = Character.toUpperCaseEx(c); 2733 if ((upperCaseChar == Character.ERROR) 2734 || (c != upperCaseChar)) { 2735 break scan; 2736 } 2737 firstLower += srcCount; 2738 } 2739 return this; 2740 } 2741 2742 /* result may grow, so i+resultOffset is the write location in result */ 2743 int resultOffset = 0; 2744 char[] result = new char[len]; /* may grow */ 2745 2746 /* Just copy the first few upperCase characters. */ 2747 System.arraycopy(value, 0, result, 0, firstLower); 2748 2749 String lang = locale.getLanguage(); 2750 boolean localeDependent = 2751 (lang == "tr" || lang == "az" || lang == "lt"); 2752 char[] upperCharArray; 2753 int upperChar; 2754 int srcChar; 2755 int srcCount; 2756 for (int i = firstLower; i < len; i += srcCount) { 2757 srcChar = (int)value[i]; 2758 if ((char)srcChar >= Character.MIN_HIGH_SURROGATE && 2759 (char)srcChar <= Character.MAX_HIGH_SURROGATE) { 2760 srcChar = codePointAt(i); 2761 srcCount = Character.charCount(srcChar); 2762 } else { 2763 srcCount = 1; 2764 } 2765 if (localeDependent) { 2766 upperChar = ConditionalSpecialCasing.toUpperCaseEx(this, i, locale); 2767 } else { 2768 upperChar = Character.toUpperCaseEx(srcChar); 2769 } 2770 if ((upperChar == Character.ERROR) 2771 || (upperChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) { 2772 if (upperChar == Character.ERROR) { 2773 if (localeDependent) { 2774 upperCharArray = 2775 ConditionalSpecialCasing.toUpperCaseCharArray(this, i, locale); 2776 } else { 2777 upperCharArray = Character.toUpperCaseCharArray(srcChar); 2778 } 2779 } else if (srcCount == 2) { 2780 resultOffset += Character.toChars(upperChar, result, i + resultOffset) - srcCount; 2781 continue; 2782 } else { 2783 upperCharArray = Character.toChars(upperChar); 2784 } 2785 2786 /* Grow result if needed */ 2787 int mapLen = upperCharArray.length; 2788 if (mapLen > srcCount) { 2789 char[] result2 = new char[result.length + mapLen - srcCount]; 2790 System.arraycopy(result, 0, result2, 0, i + resultOffset); 2791 result = result2; 2792 } 2793 for (int x = 0; x < mapLen; ++x) { 2794 result[i + resultOffset + x] = upperCharArray[x]; 2795 } 2796 resultOffset += (mapLen - srcCount); 2797 } else { 2798 result[i + resultOffset] = (char)upperChar; 2799 } 2800 } 2801 return new String(result, 0, len + resultOffset); 2802 } 2803 2804 /** 2805 * Converts all of the characters in this {@code String} to upper 2806 * case using the rules of the default locale. This method is equivalent to 2807 * {@code toUpperCase(Locale.getDefault())}. 2808 * <p> 2809 * <b>Note:</b> This method is locale sensitive, and may produce unexpected 2810 * results if used for strings that are intended to be interpreted locale 2811 * independently. 2812 * Examples are programming language identifiers, protocol keys, and HTML 2813 * tags. 2814 * For instance, {@code "title".toUpperCase()} in a Turkish locale 2815 * returns {@code "T\u005Cu0130TLE"}, where '\u005Cu0130' is the 2816 * LATIN CAPITAL LETTER I WITH DOT ABOVE character. 2817 * To obtain correct results for locale insensitive strings, use 2818 * {@code toUpperCase(Locale.ENGLISH)}. 2819 * <p> 2820 * @return the {@code String}, converted to uppercase. 2821 * @see java.lang.String#toUpperCase(Locale) 2822 */ 2823 public String toUpperCase() { 2824 return toUpperCase(Locale.getDefault()); 2825 } 2826 2827 /** 2828 * Returns a copy of the string, with leading and trailing whitespace 2829 * omitted. 2830 * <p> 2831 * If this {@code String} object represents an empty character 2832 * sequence, or the first and last characters of character sequence 2833 * represented by this {@code String} object both have codes 2834 * greater than {@code '\u005Cu0020'} (the space character), then a 2835 * reference to this {@code String} object is returned. 2836 * <p> 2837 * Otherwise, if there is no character with a code greater than 2838 * {@code '\u005Cu0020'} in the string, then a new 2839 * {@code String} object representing an empty string is created 2840 * and returned. 2841 * <p> 2842 * Otherwise, let <i>k</i> be the index of the first character in the 2843 * string whose code is greater than {@code '\u005Cu0020'}, and let 2844 * <i>m</i> be the index of the last character in the string whose code 2845 * is greater than {@code '\u005Cu0020'}. A new {@code String} 2846 * object is created, representing the substring of this string that 2847 * begins with the character at index <i>k</i> and ends with the 2848 * character at index <i>m</i>-that is, the result of 2849 * {@code this.substring(k, m + 1)}. 2850 * <p> 2851 * This method may be used to trim whitespace (as defined above) from 2852 * the beginning and end of a string. 2853 * 2854 * @return A copy of this string with leading and trailing white 2855 * space removed, or this string if it has no leading or 2856 * trailing white space. 2857 */ 2858 public String trim() { 2859 int len = value.length; 2860 int st = 0; 2861 char[] val = value; /* avoid getfield opcode */ 2862 2863 while ((st < len) && (val[st] <= ' ')) { 2864 st++; 2865 } 2866 while ((st < len) && (val[len - 1] <= ' ')) { 2867 len--; 2868 } 2869 return ((st > 0) || (len < value.length)) ? substring(st, len) : this; 2870 } 2871 2872 /** 2873 * This object (which is already a string!) is itself returned. 2874 * 2875 * @return the string itself. 2876 */ 2877 public String toString() { 2878 return this; 2879 } 2880 2881 /** 2882 * Converts this string to a new character array. 2883 * 2884 * @return a newly allocated character array whose length is the length 2885 * of this string and whose contents are initialized to contain 2886 * the character sequence represented by this string. 2887 */ 2888 public char[] toCharArray() { 2889 // Cannot use Arrays.copyOf because of class initialization order issues 2890 char result[] = new char[value.length]; 2891 System.arraycopy(value, 0, result, 0, value.length); 2892 return result; 2893 } 2894 2895 /** 2896 * Returns a formatted string using the specified format string and 2897 * arguments. 2898 * 2899 * <p> The locale always used is the one returned by {@link 2900 * java.util.Locale#getDefault() Locale.getDefault()}. 2901 * 2902 * @param format 2903 * A <a href="../util/Formatter.html#syntax">format string</a> 2904 * 2905 * @param args 2906 * Arguments referenced by the format specifiers in the format 2907 * string. If there are more arguments than format specifiers, the 2908 * extra arguments are ignored. The number of arguments is 2909 * variable and may be zero. The maximum number of arguments is 2910 * limited by the maximum dimension of a Java array as defined by 2911 * <cite>The Java™ Virtual Machine Specification</cite>. 2912 * The behaviour on a 2913 * {@code null} argument depends on the <a 2914 * href="../util/Formatter.html#syntax">conversion</a>. 2915 * 2916 * @throws java.util.IllegalFormatException 2917 * If a format string contains an illegal syntax, a format 2918 * specifier that is incompatible with the given arguments, 2919 * insufficient arguments given the format string, or other 2920 * illegal conditions. For specification of all possible 2921 * formatting errors, see the <a 2922 * href="../util/Formatter.html#detail">Details</a> section of the 2923 * formatter class specification. 2924 * 2925 * @return A formatted string 2926 * 2927 * @see java.util.Formatter 2928 * @since 1.5 2929 */ 2930 public static String format(String format, Object... args) { 2931 return new Formatter().format(format, args).toString(); 2932 } 2933 2934 /** 2935 * Returns a formatted string using the specified locale, format string, 2936 * and arguments. 2937 * 2938 * @param l 2939 * The {@linkplain java.util.Locale locale} to apply during 2940 * formatting. If {@code l} is {@code null} then no localization 2941 * is applied. 2942 * 2943 * @param format 2944 * A <a href="../util/Formatter.html#syntax">format string</a> 2945 * 2946 * @param args 2947 * Arguments referenced by the format specifiers in the format 2948 * string. If there are more arguments than format specifiers, the 2949 * extra arguments are ignored. The number of arguments is 2950 * variable and may be zero. The maximum number of arguments is 2951 * limited by the maximum dimension of a Java array as defined by 2952 * <cite>The Java™ Virtual Machine Specification</cite>. 2953 * The behaviour on a 2954 * {@code null} argument depends on the 2955 * <a href="../util/Formatter.html#syntax">conversion</a>. 2956 * 2957 * @throws java.util.IllegalFormatException 2958 * If a format string contains an illegal syntax, a format 2959 * specifier that is incompatible with the given arguments, 2960 * insufficient arguments given the format string, or other 2961 * illegal conditions. For specification of all possible 2962 * formatting errors, see the <a 2963 * href="../util/Formatter.html#detail">Details</a> section of the 2964 * formatter class specification 2965 * 2966 * @return A formatted string 2967 * 2968 * @see java.util.Formatter 2969 * @since 1.5 2970 */ 2971 public static String format(Locale l, String format, Object... args) { 2972 return new Formatter(l).format(format, args).toString(); 2973 } 2974 2975 /** 2976 * Returns the string representation of the {@code Object} argument. 2977 * 2978 * @param obj an {@code Object}. 2979 * @return if the argument is {@code null}, then a string equal to 2980 * {@code "null"}; otherwise, the value of 2981 * {@code obj.toString()} is returned. 2982 * @see java.lang.Object#toString() 2983 */ 2984 public static String valueOf(Object obj) { 2985 return (obj == null) ? "null" : obj.toString(); 2986 } 2987 2988 /** 2989 * Returns the string representation of the {@code char} array 2990 * argument. The contents of the character array are copied; subsequent 2991 * modification of the character array does not affect the newly 2992 * created string. 2993 * 2994 * @param data a {@code char} array. 2995 * @return a newly allocated string representing the same sequence of 2996 * characters contained in the character array argument. 2997 */ 2998 public static String valueOf(char data[]) { 2999 return new String(data); 3000 } 3001 3002 /** 3003 * Returns the string representation of a specific subarray of the 3004 * {@code char} array argument. 3005 * <p> 3006 * The {@code offset} argument is the index of the first 3007 * character of the subarray. The {@code count} argument 3008 * specifies the length of the subarray. The contents of the subarray 3009 * are copied; subsequent modification of the character array does not 3010 * affect the newly created string. 3011 * 3012 * @param data the character array. 3013 * @param offset the initial offset into the value of the 3014 * {@code String}. 3015 * @param count the length of the value of the {@code String}. 3016 * @return a string representing the sequence of characters contained 3017 * in the subarray of the character array argument. 3018 * @exception IndexOutOfBoundsException if {@code offset} is 3019 * negative, or {@code count} is negative, or 3020 * {@code offset+count} is larger than 3021 * {@code data.length}. 3022 */ 3023 public static String valueOf(char data[], int offset, int count) { 3024 return new String(data, offset, count); 3025 } 3026 3027 /** 3028 * Returns a String that represents the character sequence in the 3029 * array specified. 3030 * 3031 * @param data the character array. 3032 * @param offset initial offset of the subarray. 3033 * @param count length of the subarray. 3034 * @return a {@code String} that contains the characters of the 3035 * specified subarray of the character array. 3036 */ 3037 public static String copyValueOf(char data[], int offset, int count) { 3038 // All public String constructors now copy the data. 3039 return new String(data, offset, count); 3040 } 3041 3042 /** 3043 * Returns a String that represents the character sequence in the 3044 * array specified. 3045 * 3046 * @param data the character array. 3047 * @return a {@code String} that contains the characters of the 3048 * character array. 3049 */ 3050 public static String copyValueOf(char data[]) { 3051 return new String(data); 3052 } 3053 3054 /** 3055 * Returns the string representation of the {@code boolean} argument. 3056 * 3057 * @param b a {@code boolean}. 3058 * @return if the argument is {@code true}, a string equal to 3059 * {@code "true"} is returned; otherwise, a string equal to 3060 * {@code "false"} is returned. 3061 */ 3062 public static String valueOf(boolean b) { 3063 return b ? "true" : "false"; 3064 } 3065 3066 /** 3067 * Returns the string representation of the {@code char} 3068 * argument. 3069 * 3070 * @param c a {@code char}. 3071 * @return a string of length {@code 1} containing 3072 * as its single character the argument {@code c}. 3073 */ 3074 public static String valueOf(char c) { 3075 char data[] = {c}; 3076 return new String(data, true); 3077 } 3078 3079 /** 3080 * Returns the string representation of the {@code int} argument. 3081 * <p> 3082 * The representation is exactly the one returned by the 3083 * {@code Integer.toString} method of one argument. 3084 * 3085 * @param i an {@code int}. 3086 * @return a string representation of the {@code int} argument. 3087 * @see java.lang.Integer#toString(int, int) 3088 */ 3089 public static String valueOf(int i) { 3090 return Integer.toString(i); 3091 } 3092 3093 /** 3094 * Returns the string representation of the {@code long} argument. 3095 * <p> 3096 * The representation is exactly the one returned by the 3097 * {@code Long.toString} method of one argument. 3098 * 3099 * @param l a {@code long}. 3100 * @return a string representation of the {@code long} argument. 3101 * @see java.lang.Long#toString(long) 3102 */ 3103 public static String valueOf(long l) { 3104 return Long.toString(l); 3105 } 3106 3107 /** 3108 * Returns the string representation of the {@code float} argument. 3109 * <p> 3110 * The representation is exactly the one returned by the 3111 * {@code Float.toString} method of one argument. 3112 * 3113 * @param f a {@code float}. 3114 * @return a string representation of the {@code float} argument. 3115 * @see java.lang.Float#toString(float) 3116 */ 3117 public static String valueOf(float f) { 3118 return Float.toString(f); 3119 } 3120 3121 /** 3122 * Returns the string representation of the {@code double} argument. 3123 * <p> 3124 * The representation is exactly the one returned by the 3125 * {@code Double.toString} method of one argument. 3126 * 3127 * @param d a {@code double}. 3128 * @return a string representation of the {@code double} argument. 3129 * @see java.lang.Double#toString(double) 3130 */ 3131 public static String valueOf(double d) { 3132 return Double.toString(d); 3133 } 3134 3135 /** 3136 * Returns a canonical representation for the string object. 3137 * <p> 3138 * A pool of strings, initially empty, is maintained privately by the 3139 * class {@code String}. 3140 * <p> 3141 * When the intern method is invoked, if the pool already contains a 3142 * string equal to this {@code String} object as determined by 3143 * the {@link #equals(Object)} method, then the string from the pool is 3144 * returned. Otherwise, this {@code String} object is added to the 3145 * pool and a reference to this {@code String} object is returned. 3146 * <p> 3147 * It follows that for any two strings {@code s} and {@code t}, 3148 * {@code s.intern() == t.intern()} is {@code true} 3149 * if and only if {@code s.equals(t)} is {@code true}. 3150 * <p> 3151 * All literal strings and string-valued constant expressions are 3152 * interned. String literals are defined in section 3.10.5 of the 3153 * <cite>The Java™ Language Specification</cite>. 3154 * 3155 * @return a string that has the same contents as this string, but is 3156 * guaranteed to be from a pool of unique strings. 3157 */ 3158 public native String intern(); 3159 3160 /** 3161 * Seed value used for each alternative hash calculated. 3162 */ 3163 private static final int HASHING_SEED; 3164 3165 static { 3166 long nanos = System.nanoTime(); 3167 long now = System.currentTimeMillis(); 3168 int SEED_MATERIAL[] = { 3169 System.identityHashCode(String.class), 3170 System.identityHashCode(System.class), 3171 (int) (nanos >>> 32), 3172 (int) nanos, 3173 (int) (now >>> 32), 3174 (int) now, 3175 (int) (System.nanoTime() >>> 2) 3176 }; 3177 3178 // Use murmur3 to scramble the seeding material. 3179 // Inline implementation to avoid loading classes 3180 int h1 = 0; 3181 3182 // body 3183 for(int k1 : SEED_MATERIAL) { 3184 k1 *= 0xcc9e2d51; 3185 k1 = (k1 << 15) | (k1 >>> 17); 3186 k1 *= 0x1b873593; 3187 3188 h1 ^= k1; 3189 h1 = (h1 << 13) | (h1 >>> 19); 3190 h1 = h1 * 5 + 0xe6546b64; 3191 } 3192 3193 // tail (always empty, as body is always 32-bit chunks) 3194 3195 // finalization 3196 3197 h1 ^= SEED_MATERIAL.length * 4; 3198 3199 // finalization mix force all bits of a hash block to avalanche 3200 h1 ^= h1 >>> 16; 3201 h1 *= 0x85ebca6b; 3202 h1 ^= h1 >>> 13; 3203 h1 *= 0xc2b2ae35; 3204 h1 ^= h1 >>> 16; 3205 3206 HASHING_SEED = h1; 3207 } 3208 3209 /** 3210 * Cached value of the hashing algorithm result 3211 */ 3212 private transient int hash32 = 0; 3213 3214 /** 3215 * Return a 32-bit hash code value for this object. 3216 * <p> 3217 * The general contract of {@code hash32} is: 3218 * <ul> 3219 * <li>Whenever it is invoked on the same object more than once during 3220 * an execution of a Java application, the {@code hash32} method 3221 * must consistently return the same integer, provided no information 3222 * used in {@code equals} comparisons on the object is modified. 3223 * This integer need not remain consistent from one execution of an 3224 * application to another execution of the same application. 3225 * <li>If two objects are equal according to the {@code equals(Object)} 3226 * method, then calling the {@code hash32} method on each of 3227 * the two objects must produce the same integer result. 3228 * <li>It is <em>not</em> required that if two objects are unequal 3229 * according to the {@link java.lang.Object#equals(java.lang.Object)} 3230 * method, then calling the {@code hash32} method on each of the 3231 * two objects must produce distinct integer results. However, the 3232 * programmer should be aware that producing distinct integer results 3233 * for unequal objects may improve the performance of hash tables. 3234 * </ul> 3235 * 3236 * The hash value will never be zero. 3237 * 3238 * @return a hash code value for this object. 3239 * @see java.lang.Object#equals(java.lang.Object) 3240 */ 3241 public int hash32() { 3242 int h = hash32; 3243 if (0 == h) { 3244 // harmless data race on hash32 here. 3245 h = sun.misc.Hashing.murmur3_32(HASHING_SEED, value, 0, value.length); 3246 3247 // ensure result is not zero to avoid recalcing 3248 h = (0 != h) ? h : 1; 3249 3250 hash32 = h; 3251 } 3252 3253 return h; 3254 } 3255 3256 }