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