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