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