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