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