String.java 43.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
/* String.java -- immutable character sequences; the object of string literals
   Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003
   Free Software Foundation, Inc.

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */
Tom Tromey committed
38 39 40


package java.lang;
41

Tom Tromey committed
42
import java.io.Serializable;
43
import java.io.UnsupportedEncodingException;
Tom Tromey committed
44
import java.lang.Comparable;
45
import java.util.Comparator;
46
import java.util.Locale;
47 48
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
Tom Tromey committed
49 50

/**
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
 * Strings represent an immutable set of characters.  All String literals
 * are instances of this class, and two string literals with the same contents
 * refer to the same String object.
 *
 * <p>This class also includes a number of methods for manipulating the
 * contents of strings (of course, creating a new object if there are any
 * changes, as String is immutable). Case mapping relies on Unicode 3.0.0
 * standards, where some character sequences have a different number of
 * characters in the uppercase version than the lower case.
 *
 * <p>Strings are special, in that they are the only object with an overloaded
 * operator. When you use '+' with at least one String argument, both
 * arguments have String conversion performed on them, and another String (not
 * guaranteed to be unique) results.
 *
 * <p>String is special-cased when doing data serialization - rather than
 * listing the fields of this class, a String object is converted to a string
 * literal in the object stream.
 *
 * @author Paul N. Fisher
71 72
 * @author Eric Blake (ebb9@email.byu.edu)
 * @author Per Bothner (bothner@cygnus.com)
73 74
 * @since 1.0
 * @status updated to 1.4
Tom Tromey committed
75
 */
76
public final class String implements Serializable, Comparable, CharSequence
Tom Tromey committed
77
{
78 79 80 81 82 83 84 85 86
  // WARNING: String is a CORE class in the bootstrap cycle. See the comments
  // in vm/reference/java/lang/Runtime for implications of this fact.

  /**
   * This is probably not necessary because this class is special cased already
   * but it will avoid showing up as a discrepancy when comparing SUIDs.
   */
  private static final long serialVersionUID = -6849794470754667710L;

87 88 89 90 91 92 93
  /**
   * This is the object that holds the characters that make up the
   * String.  It might be a char[], or it could be String.  It could
   * even be `this'.  The actual characters can't be located using
   * pure Java code.
   * @see #boffset
   */
Tom Tromey committed
94
  private Object data;
95 96 97 98 99 100 101 102 103 104 105 106

  /**
   * This is a <emph>byte</emph> offset of the actual characters from
   * the start of the character-holding object.  Don't use this field
   * in Java code.
   */
  private int boffset;

  /**
   * Holds the number of characters in value.  Package visible for use
   * by trusted code.
   */
107
  int count;
Tom Tromey committed
108

109
  /**
110 111 112 113 114 115
   * Caches the result of hashCode().  If this value is zero, the hashcode
   * is considered uncached (even if 0 is the correct hash value).
   */
  private int cachedHashCode;

  /**
116
   * An implementation for {@link CASE_INSENSITIVE_ORDER}.
117 118
   * This must be {@link Serializable}. The class name is dictated by
   * compatibility with Sun's JDK.
119 120 121
   */
  private static final class CaseInsensitiveComparator
    implements Comparator, Serializable
122
  {
123
    /**
124 125 126 127 128 129
     * Compatible with JDK 1.2.
     */
    private static final long serialVersionUID = 8575799808933029326L;

    /**
     * The default private constructor generates unnecessary overhead.
130 131 132 133
     */
    CaseInsensitiveComparator() {}

    /**
134
     * Compares to Strings, using
135
     * <code>String.compareToIgnoreCase(String)</code>.
136
     *
137 138 139 140 141 142 143 144 145
     * @param o1 the first string
     * @param o2 the second string
     * @return &lt; 0, 0, or &gt; 0 depending on the case-insensitive
     *         comparison of the two strings.
     * @throws NullPointerException if either argument is null
     * @throws ClassCastException if either argument is not a String
     * @see #compareToIgnoreCase(String)
     */
    public int compare(Object o1, Object o2)
146
    {
147
      return ((String) o1).compareToIgnoreCase((String) o2);
148
    }
149
  } // class CaseInsensitiveComparator
150 151 152

  /**
   * A Comparator that uses <code>String.compareToIgnoreCase(String)</code>.
153 154
   * This comparator is {@link Serializable}. Note that it ignores Locale,
   * for that, you want a Collator.
155
   *
156
   * @see Collator#compare(String, String)
157 158 159 160
   * @since 1.2
   */
  public static final Comparator CASE_INSENSITIVE_ORDER
    = new CaseInsensitiveComparator();
161

162 163 164 165
  /**
   * Creates an empty String (length 0). Unless you really need a new object,
   * consider using <code>""</code> instead.
   */
166
  public String()
Tom Tromey committed
167
  {
168 169 170
    data = "".data;
    boffset = 0;
    count = 0;
Tom Tromey committed
171 172
  }

173 174 175 176 177 178 179
  /**
   * Copies the contents of a String to a new String. Since Strings are
   * immutable, only a shallow copy is performed.
   *
   * @param str String to copy
   * @throws NullPointerException if value is null
   */
180
  public String(String str)
Tom Tromey committed
181
  {
182 183 184
    data = str.data;
    boffset = str.boffset;
    count = str.count;
185
    cachedHashCode = str.cachedHashCode;
Tom Tromey committed
186 187
  }

188 189 190 191 192 193 194
  /**
   * Creates a new String using the character sequence of the char array.
   * Subsequent changes to data do not affect the String.
   *
   * @param data char array to copy
   * @throws NullPointerException if data is null
   */
195
  public String(char[] data)
Tom Tromey committed
196
  {
197
    init(data, 0, data.length, false);
Tom Tromey committed
198 199
  }

200 201 202 203 204 205 206 207 208 209
  /**
   * Creates a new String using the character sequence of a subarray of
   * characters. The string starts at offset, and copies count chars.
   * Subsequent changes to data do not affect the String.
   *
   * @param data char array to copy
   * @param offset position (base 0) to start copying out of data
   * @param count the number of characters from data to copy
   * @throws NullPointerException if data is null
   * @throws IndexOutOfBoundsException if (offset &lt; 0 || count &lt; 0
210
   *         || offset + count &gt; data.length)
211 212
   *         (while unspecified, this is a StringIndexOutOfBoundsException)
   */
213
  public String(char[] data, int offset, int count)
214
  {
215
    init(data, offset, count, false);
216 217
  }

218 219 220 221 222 223
  /**
   * Creates a new String using an 8-bit array of integer values, starting at
   * an offset, and copying up to the count. Each character c, using
   * corresponding byte b, is created in the new String as if by performing:
   *
   * <pre>
224
   * c = (char) (((hibyte &amp; 0xff) &lt;&lt; 8) | (b &amp; 0xff))
225 226 227 228 229 230 231 232
   * </pre>
   *
   * @param ascii array of integer values
   * @param hibyte top byte of each Unicode character
   * @param offset position (base 0) to start copying out of ascii
   * @param count the number of characters from ascii to copy
   * @throws NullPointerException if ascii is null
   * @throws IndexOutOfBoundsException if (offset &lt; 0 || count &lt; 0
233
   *         || offset + count &gt; ascii.length)
234 235 236 237 238 239 240 241
   *         (while unspecified, this is a StringIndexOutOfBoundsException)
   * @see #String(byte[])
   * @see #String(byte[], String)
   * @see #String(byte[], int, int)
   * @see #String(byte[], int, int, String)
   * @deprecated use {@link #String(byte[], int, int, String)} to perform
   *             correct encoding
   */
242
  public String(byte[] ascii, int hibyte, int offset, int count)
Tom Tromey committed
243
  {
244
    init(ascii, hibyte, offset, count);
Tom Tromey committed
245 246
  }

247 248 249 250 251 252
  /**
   * Creates a new String using an 8-bit array of integer values. Each
   * character c, using corresponding byte b, is created in the new String
   * as if by performing:
   *
   * <pre>
253
   * c = (char) (((hibyte &amp; 0xff) &lt;&lt; 8) | (b &amp; 0xff))
254 255 256 257 258 259 260 261 262 263 264 265 266
   * </pre>
   *
   * @param ascii array of integer values
   * @param hibyte top byte of each Unicode character
   * @throws NullPointerException if ascii is null
   * @see #String(byte[])
   * @see #String(byte[], String)
   * @see #String(byte[], int, int)
   * @see #String(byte[], int, int, String)
   * @see #String(byte[], int, int, int)
   * @deprecated use {@link #String(byte[], String)} to perform
   *             correct encoding
   */
267
  public String(byte[] ascii, int hibyte)
Tom Tromey committed
268
  {
269
    init(ascii, hibyte, 0, ascii.length);
Tom Tromey committed
270 271
  }

272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
  /**
   * Creates a new String using the portion of the byte array starting at the
   * offset and ending at offset + count. Uses the specified encoding type
   * to decode the byte array, so the resulting string may be longer or
   * shorter than the byte array. For more decoding control, use
   * {@link java.nio.charset.CharsetDecoder}, and for valid character sets,
   * see {@link java.nio.charset.Charset}. The behavior is not specified if
   * the decoder encounters invalid characters; this implementation throws
   * an Error.
   *
   * @param data byte array to copy
   * @param offset the offset to start at
   * @param count the number of characters in the array to use
   * @param encoding the name of the encoding to use
   * @throws NullPointerException if data or encoding is null
   * @throws IndexOutOfBoundsException if offset or count is incorrect
   *         (while unspecified, this is a StringIndexOutOfBoundsException)
   * @throws UnsupportedEncodingException if encoding is not found
   * @throws Error if the decoding fails
   * @since 1.1
   */
293
  public String(byte[] data, int offset, int count, String encoding)
294
    throws UnsupportedEncodingException
295
  {
296
    init (data, offset, count, encoding);
297 298
  }

299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
  /**
   * Creates a new String using the byte array. Uses the specified encoding
   * type to decode the byte array, so the resulting string may be longer or
   * shorter than the byte array. For more decoding control, use
   * {@link java.nio.charset.CharsetDecoder}, and for valid character sets,
   * see {@link java.nio.charset.Charset}. The behavior is not specified if
   * the decoder encounters invalid characters; this implementation throws
   * an Error.
   *
   * @param data byte array to copy
   * @param encoding the name of the encoding to use
   * @throws NullPointerException if data or encoding is null
   * @throws UnsupportedEncodingException if encoding is not found
   * @throws Error if the decoding fails
   * @see #String(byte[], int, int, String)
   * @since 1.1
   */
316
  public String(byte[] data, String encoding)
317
    throws UnsupportedEncodingException
Tom Tromey committed
318
  {
319
    this(data, 0, data.length, encoding);
Tom Tromey committed
320 321
  }

322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
  /**
   * Creates a new String using the portion of the byte array starting at the
   * offset and ending at offset + count. Uses the encoding of the platform's
   * default charset, so the resulting string may be longer or shorter than
   * the byte array. For more decoding control, use
   * {@link java.nio.charset.CharsetDecoder}.  The behavior is not specified
   * if the decoder encounters invalid characters; this implementation throws
   * an Error.
   *
   * @param data byte array to copy
   * @param offset the offset to start at
   * @param count the number of characters in the array to use
   * @throws NullPointerException if data is null
   * @throws IndexOutOfBoundsException if offset or count is incorrect
   * @throws Error if the decoding fails
   * @see #String(byte[], int, int, String)
   * @since 1.1
   */
340
  public String(byte[] data, int offset, int count)
Tom Tromey committed
341 342 343
  {
    try
      {
344
	init (data, offset, count,
Tom Tromey committed
345 346 347 348 349 350 351
	      System.getProperty("file.encoding", "8859_1"));
      }
    catch (UnsupportedEncodingException x1)
      {
	// Maybe the default encoding is bad.
	try
	  {
352
	    init (data, offset, count, "8859_1");
Tom Tromey committed
353 354 355 356 357 358 359 360
	  }
	catch (UnsupportedEncodingException x2)
	  {
	    // We know this can't happen.
	  }
      }
  }

361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
  /**
   * Creates a new String using the byte array. Uses the encoding of the
   * platform's default charset, so the resulting string may be longer or
   * shorter than the byte array. For more decoding control, use
   * {@link java.nio.charset.CharsetDecoder}.  The behavior is not specified
   * if the decoder encounters invalid characters; this implementation throws
   * an Error.
   *
   * @param data byte array to copy
   * @throws NullPointerException if data is null
   * @throws Error if the decoding fails
   * @see #String(byte[], int, int)
   * @see #String(byte[], int, int, String)
   * @since 1.1
   */
376
  public String(byte[] data)
Tom Tromey committed
377
  {
378
    this(data, 0, data.length);
Tom Tromey committed
379 380
  }

381 382 383 384 385 386 387
  /**
   * Creates a new String using the character sequence represented by
   * the StringBuffer. Subsequent changes to buf do not affect the String.
   *
   * @param buffer StringBuffer to copy
   * @throws NullPointerException if buffer is null
   */
388
  public String(StringBuffer buffer)
Tom Tromey committed
389
  {
390 391
    synchronized (buffer)
      {
392 393 394 395 396
	// Share unless buffer is 3/4 empty.
	boolean should_copy = ((buffer.count << 2) < buffer.value.length);
	if (! should_copy)
	  buffer.shared = true;
	init (buffer.value, 0, buffer.count, ! should_copy);
397
      }
Tom Tromey committed
398 399
  }

400 401 402 403 404 405 406 407 408 409
  /**
   * Special constructor which can share an array when safe to do so.
   *
   * @param data the characters to copy
   * @param offset the location to start from
   * @param count the number of characters to use
   * @param dont_copy true if the array is trusted, and need not be copied
   * @throws NullPointerException if chars is null
   * @throws StringIndexOutOfBoundsException if bounds check fails
   */
410
  String(char[] data, int offset, int count, boolean dont_copy)
Tom Tromey committed
411
  {
412
    init(data, offset, count, dont_copy);
Tom Tromey committed
413 414
  }

415 416 417
  // This is used by gnu.gcj.runtime.StringBuffer, so it must have
  // package-private protection.  It is accessed via CNI and so avoids
  // ordinary protection mechanisms.
418
  String(gnu.gcj.runtime.StringBuffer buffer)
Tom Tromey committed
419
  {
420 421
    // No need to synchronize or mark the buffer, since we know it is
    // only used once.
422
    init (buffer);
Tom Tromey committed
423 424
  }

425 426 427 428 429 430
  /**
   * Returns the number of characters contained in this String.
   *
   * @return the length of this String
   */
  public int length()
Tom Tromey committed
431 432 433 434
  {
    return count;
  }

435 436 437 438 439 440 441 442
  /**
   * Returns the character located at the specified index within this String.
   *
   * @param index position of character to return (base 0)
   * @return character located at position index
   * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt;= length()
   *         (while unspecified, this is a StringIndexOutOfBoundsException)
   */
443
  public native char charAt(int index);
Tom Tromey committed
444

445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
  /**
   * Copies characters from this String starting at a specified start index,
   * ending at a specified stop index, to a character array starting at
   * a specified destination begin index.
   *
   * @param srcBegin index to begin copying characters from this String
   * @param srcEnd index after the last character to be copied from this String
   * @param dst character array which this String is copied into
   * @param dstBegin index to start writing characters into dst
   * @throws NullPointerException if dst is null
   * @throws IndexOutOfBoundsException if any indices are out of bounds
   *         (while unspecified, source problems cause a
   *         StringIndexOutOfBoundsException, and dst problems cause an
   *         ArrayIndexOutOfBoundsException)
   */
460 461
  public native void getChars(int srcBegin, int srcEnd,
			      char[] dst, int dstBegin);
Tom Tromey committed
462

463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
  /**
   * Copies the low byte of each character from this String starting at a
   * specified start index, ending at a specified stop index, to a byte array
   * starting at a specified destination begin index.
   *
   * @param srcBegin index to being copying characters from this String
   * @param srcEnd index after the last character to be copied from this String
   * @param dst byte array which each low byte of this String is copied into
   * @param dstBegin index to start writing characters into dst
   * @throws NullPointerException if dst is null and copy length is non-zero
   * @throws IndexOutOfBoundsException if any indices are out of bounds
   *         (while unspecified, source problems cause a
   *         StringIndexOutOfBoundsException, and dst problems cause an
   *         ArrayIndexOutOfBoundsException)
   * @see #getBytes()
   * @see #getBytes(String)
   * @deprecated use {@link #getBytes()}, which uses a char to byte encoder
   */
481 482
  public native void getBytes(int srcBegin, int srcEnd,
			      byte[] dst, int dstBegin);
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497

  /**
   * Converts the Unicode characters in this String to a byte array. Uses the
   * specified encoding method, so the result may be longer or shorter than
   * the String. For more encoding control, use
   * {@link java.nio.charset.CharsetEncoder}, and for valid character sets,
   * see {@link java.nio.charset.Charset}. The behavior is not specified if
   * the encoder encounters a problem; this implementation returns null.
   *
   * @param enc encoding name
   * @return the resulting byte array, or null on a problem
   * @throws NullPointerException if enc is null
   * @throws UnsupportedEncodingException if encoding is not supported
   * @since 1.1
   */
498
  public native byte[] getBytes(String enc)
499 500 501 502 503 504 505 506 507 508 509 510
    throws UnsupportedEncodingException;

  /**
   * Converts the Unicode characters in this String to a byte array. Uses the
   * encoding of the platform's default charset, so the result may be longer
   * or shorter than the String. For more encoding control, use
   * {@link java.nio.charset.CharsetEncoder}.  The behavior is not specified if
   * the encoder encounters a problem; this implementation returns null.
   *
   * @return the resulting byte array, or null on a problem
   * @since 1.1
   */
511
  public byte[] getBytes()
Tom Tromey committed
512
  {
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
    try
      {
	return getBytes (System.getProperty("file.encoding", "8859_1"));
      }
    catch (UnsupportedEncodingException x)
      {
	// This probably shouldn't happen, but could if file.encoding
	// is somehow changed to a value we don't understand.
	try
	  {
	    return getBytes ("8859_1");
	  }
	catch (UnsupportedEncodingException x2)
	  {
	    // This really shouldn't happen, because the 8859_1
	    // encoding should always be available.
	    throw new InternalError ("couldn't find 8859_1 encoder");
	  }
      }
Tom Tromey committed
532 533
  }

534 535 536 537 538 539 540 541 542
  /**
   * Predicate which compares anObject to this. This is true only for Strings
   * with the same character sequence.
   *
   * @param anObject the object to compare
   * @return true if anObject is semantically equal to this
   * @see #compareTo(String)
   * @see #equalsIgnoreCase(String)
   */
543
  public native boolean equals(Object anObject);
Tom Tromey committed
544

545
  /**
546 547 548 549 550 551 552 553 554 555 556
   * Compares the given StringBuffer to this String. This is true if the
   * StringBuffer has the same content as this String at this moment.
   *
   * @param buffer the StringBuffer to compare to
   * @return true if StringBuffer has the same character sequence
   * @throws NullPointerException if the given StringBuffer is null
   * @since 1.4
   */
  public native boolean contentEquals(StringBuffer buffer);

  /**
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
   * Compares a String to this String, ignoring case. This does not handle
   * multi-character capitalization exceptions; instead the comparison is
   * made on a character-by-character basis, and is true if:<br><ul>
   * <li><code>c1 == c2</code></li>
   * <li><code>Character.toUpperCase(c1)
   *     == Character.toUpperCase(c2)</code></li>
   * <li><code>Character.toLowerCase(c1)
   *     == Character.toLowerCase(c2)</code></li>
   * </ul>
   *
   * @param anotherString String to compare to this String
   * @return true if anotherString is equal, ignoring case
   * @see #equals(Object)
   * @see Character#toUpperCase(char)
   * @see Character#toLowerCase(char)
   */
573
  public native boolean equalsIgnoreCase(String anotherString);
Tom Tromey committed
574

575 576 577 578 579 580 581 582 583 584 585 586 587 588
  /**
   * Compares this String and another String (case sensitive,
   * lexicographically). The result is less than 0 if this string sorts
   * before the other, 0 if they are equal, and greater than 0 otherwise.
   * After any common starting sequence is skipped, the result is
   * <code>this.charAt(k) - anotherString.charAt(k)</code> if both strings
   * have characters remaining, or
   * <code>this.length() - anotherString.length()</code> if one string is
   * a subsequence of the other.
   *
   * @param anotherString the String to compare against
   * @return the comparison
   * @throws NullPointerException if anotherString is null
   */
589
  public native int compareTo(String anotherString);
Tom Tromey committed
590

591 592 593 594 595 596 597 598 599 600 601 602
  /**
   * Behaves like <code>compareTo(java.lang.String)</code> unless the Object
   * is not a <code>String</code>.  Then it throws a
   * <code>ClassCastException</code>.
   *
   * @param o the object to compare against
   * @return the comparison
   * @throws NullPointerException if o is null
   * @throws ClassCastException if o is not a <code>String</code>
   * @since 1.2
   */
  public int compareTo(Object o)
Tom Tromey committed
603
  {
604
    return compareTo((String) o);
Tom Tromey committed
605
  }
606 607 608 609 610 611 612 613 614 615

  /**
   * Compares this String and another String (case insensitive). This
   * comparison is <em>similar</em> to equalsIgnoreCase, in that it ignores
   * locale and multi-characater capitalization, and compares characters
   * after performing
   * <code>Character.toLowerCase(Character.toUpperCase(c))</code> on each
   * character of the string. This is unsatisfactory for locale-based
   * comparison, in which case you should use {@link java.text.Collator}.
   *
616
   * @param str the string to compare against
617 618 619 620
   * @return the comparison
   * @see Collator#compare(String, String)
   * @since 1.2
   */
621
  public int compareToIgnoreCase(String str)
622 623 624 625
  {
    return this.toUpperCase().toLowerCase().compareTo(
     str.toUpperCase().toLowerCase());
  }  
Tom Tromey committed
626

627 628 629 630 631 632 633 634
  /**
   * Predicate which determines if this String matches another String
   * starting at a specified offset for each String and continuing
   * for a specified length. Indices out of bounds are harmless, and give
   * a false result.
   *
   * @param toffset index to start comparison at for this String
   * @param other String to compare region to this String
635
   * @param ooffset index to start comparison at for other
636 637 638 639
   * @param len number of characters to compare
   * @return true if regions match (case sensitive)
   * @throws NullPointerException if other is null
   */
640 641
  public native boolean regionMatches(int toffset,
				      String other, int ooffset, int len);
Tom Tromey committed
642

643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
  /**
   * Predicate which determines if this String matches another String
   * starting at a specified offset for each String and continuing
   * for a specified length, optionally ignoring case. Indices out of bounds
   * are harmless, and give a false result. Case comparisons are based on
   * <code>Character.toLowerCase()</code> and
   * <code>Character.toUpperCase()</code>, not on multi-character
   * capitalization expansions.
   *
   * @param ignoreCase true if case should be ignored in comparision
   * @param toffset index to start comparison at for this String
   * @param other String to compare region to this String
   * @param oofset index to start comparison at for other
   * @param len number of characters to compare
   * @return true if regions match, false otherwise
   * @throws NullPointerException if other is null
   */
660 661
  public native boolean regionMatches(boolean ignoreCase, int toffset,
				      String other, int ooffset, int len);
Tom Tromey committed
662

663 664 665 666 667 668 669 670 671 672 673 674
  /**
   * Predicate which determines if this String contains the given prefix,
   * beginning comparison at toffset. The result is false if toffset is
   * negative or greater than this.length(), otherwise it is the same as
   * <code>this.subString(toffset).startsWith(prefix)</code>.
   *
   * @param prefix String to compare
   * @param toffset offset for this String where comparison starts
   * @return true if this String starts with prefix
   * @throws NullPointerException if prefix is null
   * @see #regionMatches(boolean, int, String, int, int)
   */
675
  public native boolean startsWith(String prefix, int toffset);
676 677 678 679 680

  /**
   * Predicate which determines if this String starts with a given prefix.
   * If the prefix is an empty String, true is returned.
   *
681
   * @param prefix String to compare
682 683 684 685
   * @return true if this String starts with the prefix
   * @throws NullPointerException if prefix is null
   * @see #startsWith(String, int)
   */
686
  public boolean startsWith(String prefix)
Tom Tromey committed
687 688 689 690
  {
    return startsWith (prefix, 0);
  }

691 692 693 694 695 696 697 698 699
  /**
   * Predicate which determines if this String ends with a given suffix.
   * If the suffix is an empty String, true is returned.
   *
   * @param suffix String to compare
   * @return true if this String ends with the suffix
   * @throws NullPointerException if suffix is null
   * @see #regionMatches(boolean, int, String, int, int)
   */
700
  public boolean endsWith(String suffix)
Tom Tromey committed
701 702 703 704
  {
    return regionMatches (this.count - suffix.count, suffix, 0, suffix.count);
  }

705 706 707 708 709 710 711
  /**
   * Computes the hashcode for this String. This is done with int arithmetic,
   * where ** represents exponentiation, by this formula:<br>
   * <code>s[0]*31**(n-1) + s[1]*31**(n-2) + ... + s[n-1]</code>.
   *
   * @return hashcode value of this String
   */
712
  public native int hashCode();
Tom Tromey committed
713

714 715 716 717 718 719
  /**
   * Finds the first instance of a character in this String.
   *
   * @param ch character to find
   * @return location (base 0) of the character, or -1 if not found
   */
720
  public int indexOf(int ch)
Tom Tromey committed
721
  {
722
    return indexOf(ch, 0);
Tom Tromey committed
723 724
  }

725 726 727 728 729 730 731 732 733 734
  /**
   * Finds the first instance of a character in this String, starting at
   * a given index.  If starting index is less than 0, the search
   * starts at the beginning of this String.  If the starting index
   * is greater than the length of this String, -1 is returned.
   *
   * @param ch character to find
   * @param fromIndex index to start the search
   * @return location (base 0) of the character, or -1 if not found
   */
735
  public native int indexOf(int ch, int fromIndex);
Tom Tromey committed
736

737 738 739 740 741 742
  /**
   * Finds the last instance of a character in this String.
   *
   * @param ch character to find
   * @return location (base 0) of the character, or -1 if not found
   */
743
  public int lastIndexOf(int ch)
Tom Tromey committed
744
  {
745
    return lastIndexOf(ch, count - 1);
Tom Tromey committed
746 747
  }

748 749 750 751 752 753 754 755 756 757
  /**
   * Finds the last instance of a character in this String, starting at
   * a given index.  If starting index is greater than the maximum valid
   * index, then the search begins at the end of this String.  If the
   * starting index is less than zero, -1 is returned.
   *
   * @param ch character to find
   * @param fromIndex index to start the search
   * @return location (base 0) of the character, or -1 if not found
   */
758
  public native int lastIndexOf(int ch, int fromIndex);
Tom Tromey committed
759

760 761 762 763 764 765 766
  /**
   * Finds the first instance of a String in this String.
   *
   * @param str String to find
   * @return location (base 0) of the String, or -1 if not found
   * @throws NullPointerException if str is null
   */
767
  public int indexOf(String str)
Tom Tromey committed
768
  {
769
    return indexOf(str, 0);
Tom Tromey committed
770 771
  }

772 773 774 775 776 777 778 779 780 781 782
  /**
   * Finds the first instance of a String in this String, starting at
   * a given index.  If starting index is less than 0, the search
   * starts at the beginning of this String.  If the starting index
   * is greater than the length of this String, -1 is returned.
   *
   * @param str String to find
   * @param fromIndex index to start the search
   * @return location (base 0) of the String, or -1 if not found
   * @throws NullPointerException if str is null
   */
783
  public native int indexOf(String str, int fromIndex);
Tom Tromey committed
784

785 786 787 788 789 790 791
  /**
   * Finds the last instance of a String in this String.
   *
   * @param str String to find
   * @return location (base 0) of the String, or -1 if not found
   * @throws NullPointerException if str is null
   */
792
  public int lastIndexOf(String str)
Tom Tromey committed
793
  {
794
    return lastIndexOf(str, count - str.count);
Tom Tromey committed
795 796
  }

797 798 799 800 801 802 803 804 805 806 807
  /**
   * Finds the last instance of a String in this String, starting at
   * a given index.  If starting index is greater than the maximum valid
   * index, then the search begins at the end of this String.  If the
   * starting index is less than zero, -1 is returned.
   *
   * @param str String to find
   * @param fromIndex index to start the search
   * @return location (base 0) of the String, or -1 if not found
   * @throws NullPointerException if str is null
   */
808
  public int lastIndexOf(String str, int fromIndex)
Tom Tromey committed
809 810 811 812 813 814 815 816 817 818 819 820
  {
    if (fromIndex >= count)
      fromIndex = count - str.count;
    for (;; --fromIndex)
      {
	if (fromIndex < 0)
	  return -1;
	if (startsWith(str, fromIndex))
	  return fromIndex;
      }
  }

821 822
  /**
   * Creates a substring of this String, starting at a specified index
823 824 825 826 827 828 829
   * and ending at the end of this String.
   *
   * @param begin index to start substring (base 0)
   * @return new String which is a substring of this String
   * @throws IndexOutOfBoundsException if begin &lt; 0 || begin &gt; length()
   *         (while unspecified, this is a StringIndexOutOfBoundsException)
   */
830
  public String substring(int begin)
831
  {
832
    return substring(begin, count);
833 834 835 836
  }

  /**
   * Creates a substring of this String, starting at a specified index
837
   * and ending at one character before a specified index.
838 839 840
   *
   * @param begin index to start substring (inclusive, base 0)
   * @param end index to end at (exclusive)
841
   * @return new String which is a substring of this String
842
   * @throws IndexOutOfBoundsException if begin &lt; 0 || end &gt; length()
843
   *         || begin &gt; end (while unspecified, this is a
844 845
   *         StringIndexOutOfBoundsException)
   */
846
  public native String substring(int begin, int end);
847 848 849 850

  /**
   * Creates a substring of this String, starting at a specified index
   * and ending at one character before a specified index. This behaves like
851
   * <code>substring(begin, end)</code>.
852
   *
853 854
   * @param begin index to start substring (inclusive, base 0)
   * @param end index to end at (exclusive)
855 856
   * @return new String which is a substring of this String
   * @throws IndexOutOfBoundsException if begin &lt; 0 || end &gt; length()
857
   *         || begin &gt; end
858
   * @since 1.4
859
   */
860
  public CharSequence subSequence(int begin, int end)
861
  {
862
    return substring(begin, end);
863 864
  }

865 866 867 868 869 870 871 872
  /**
   * Concatenates a String to this String. This results in a new string unless
   * one of the two originals is "".
   *
   * @param str String to append to this String
   * @return newly concatenated String
   * @throws NullPointerException if str is null
   */
873
  public native String concat(String str);
Tom Tromey committed
874

875 876 877 878 879 880 881 882
  /**
   * Replaces every instance of a character in this String with a new
   * character. If no replacements occur, this is returned.
   *
   * @param oldChar the old character to replace
   * @param newChar the new character
   * @return new String with all instances of oldChar replaced with newChar
   */
883
  public native String replace(char oldChar, char newChar);
Tom Tromey committed
884

885
  /**
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
   * Test if this String matches a regular expression. This is shorthand for
   * <code>{@link Pattern}.matches(regex, this)</code>.
   *
   * @param regex the pattern to match
   * @return true if the pattern matches
   * @throws NullPointerException if regex is null
   * @throws PatternSyntaxException if regex is invalid
   * @see Pattern#matches(String, CharSequence)
   * @since 1.4
   */
  public boolean matches(String regex)
  {
    return Pattern.matches(regex, this);
  }

  /**
   * Replaces the first substring match of the regular expression with a
   * given replacement. This is shorthand for <code>{@link Pattern}
   *   .compile(regex).matcher(this).replaceFirst(replacement)</code>.
   *
   * @param regex the pattern to match
   * @param replacement the replacement string
   * @return the modified string
   * @throws NullPointerException if regex or replacement is null
   * @throws PatternSyntaxException if regex is invalid
   * @see #replaceAll(String, String)
   * @see Pattern#compile(String)
   * @see Pattern#matcher(CharSequence)
   * @see Matcher#replaceFirst(String)
   * @since 1.4
   */
  public String replaceFirst(String regex, String replacement)
  {
    return Pattern.compile(regex).matcher(this).replaceFirst(replacement);
  }

  /**
   * Replaces all matching substrings of the regular expression with a
   * given replacement. This is shorthand for <code>{@link Pattern}
   *   .compile(regex).matcher(this).replaceAll(replacement)</code>.
   *
   * @param regex the pattern to match
   * @param replacement the replacement string
   * @return the modified string
   * @throws NullPointerException if regex or replacement is null
   * @throws PatternSyntaxException if regex is invalid
   * @see #replaceFirst(String, String)
   * @see Pattern#compile(String)
   * @see Pattern#matcher(CharSequence)
   * @see Matcher#replaceAll(String)
   * @since 1.4
   */
  public String replaceAll(String regex, String replacement)
  {
    return Pattern.compile(regex).matcher(this).replaceAll(replacement);
  }

  /**
   * Split this string around the matches of a regular expression. Each
   * element of the returned array is the largest block of characters not
   * terminated by the regular expression, in the order the matches are found.
   *
   * <p>The limit affects the length of the array. If it is positive, the
   * array will contain at most n elements (n - 1 pattern matches). If
   * negative, the array length is unlimited, but there can be trailing empty
   * entries. if 0, the array length is unlimited, and trailing empty entries
   * are discarded.
   *
   * <p>For example, splitting "boo:and:foo" yields:<br>
   * <table border=0>
   * <th><td>Regex</td> <td>Limit</td> <td>Result</td></th>
   * <tr><td>":"</td>   <td>2</td>  <td>{ "boo", "and:foo" }</td></tr>
   * <tr><td>":"</td>   <td>t</td>  <td>{ "boo", "and", "foo" }</td></tr>
   * <tr><td>":"</td>   <td>-2</td> <td>{ "boo", "and", "foo" }</td></tr>
   * <tr><td>"o"</td>   <td>5</td>  <td>{ "b", "", ":and:f", "", "" }</td></tr>
   * <tr><td>"o"</td>   <td>-2</td> <td>{ "b", "", ":and:f", "", "" }</td></tr>
   * <tr><td>"o"</td>   <td>0</td>  <td>{ "b", "", ":and:f" }</td></tr>
   * </table>
   *
   * <p>This is shorthand for
   * <code>{@link Pattern}.compile(regex).split(this, limit)</code>.
   *
   * @param regex the pattern to match
   * @param limit the limit threshold
   * @return the array of split strings
   * @throws NullPointerException if regex or replacement is null
   * @throws PatternSyntaxException if regex is invalid
   * @see Pattern#compile(String)
   * @see Pattern#split(CharSequence, int)
   * @since 1.4
   */
  public String[] split(String regex, int limit)
  {
    return Pattern.compile(regex).split(this, limit);
  }

  /**
   * Split this string around the matches of a regular expression. Each
   * element of the returned array is the largest block of characters not
   * terminated by the regular expression, in the order the matches are found.
   * The array length is unlimited, and trailing empty entries are discarded,
   * as though calling <code>split(regex, 0)</code>.
   *
   * @param regex the pattern to match
   * @return the array of split strings
   * @throws NullPointerException if regex or replacement is null
   * @throws PatternSyntaxException if regex is invalid
   * @see #split(String, int)
   * @see Pattern#compile(String)
   * @see Pattern#split(CharSequence, int)
   * @since 1.4
   */
  public String[] split(String regex)
  {
    return Pattern.compile(regex).split(this, 0);
  }

  /**
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
   * Lowercases this String according to a particular locale. This uses
   * Unicode's special case mappings, as applied to the given Locale, so the
   * resulting string may be a different length.
   *
   * @param loc locale to use
   * @return new lowercased String, or this if no characters were lowercased
   * @throws NullPointerException if loc is null
   * @see #toUpperCase(Locale)
   * @since 1.1
   */
1014
  public native String toLowerCase(Locale locale);
1015

1016 1017 1018 1019 1020 1021 1022 1023 1024
  /**
   * Lowercases this String. This uses Unicode's special case mappings, as
   * applied to the platform's default Locale, so the resulting string may
   * be a different length.
   *
   * @return new lowercased String, or this if no characters were lowercased
   * @see #toLowerCase(Locale)
   * @see #toUpperCase()
   */
1025
  public String toLowerCase()
1026 1027 1028 1029 1030 1031 1032
  {
    // The JDK is a bit confused about what to do here.  If we pass in
    // the default Locale then special Locale handling might be
    // invoked.  However, the docs also say that Character.toLowerCase
    // rules here.  We go with the latter.
    return toLowerCase (null);
  }
Tom Tromey committed
1033

1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
  /**
   * Uppercases this String according to a particular locale. This uses
   * Unicode's special case mappings, as applied to the given Locale, so the
   * resulting string may be a different length.
   *
   * @param loc locale to use
   * @return new uppercased String, or this if no characters were uppercased
   * @throws NullPointerException if loc is null
   * @see #toLowerCase(Locale)
   * @since 1.1
   */
1045
  public native String toUpperCase(Locale locale);
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055

  /**
   * Uppercases this String. This uses Unicode's special case mappings, as
   * applied to the platform's default Locale, so the resulting string may
   * be a different length.
   *
   * @return new uppercased String, or this if no characters were uppercased
   * @see #toUpperCase(Locale)
   * @see #toLowerCase()
   */
1056
  public String toUpperCase()
1057 1058 1059 1060 1061 1062 1063
  {
    // The JDK is a bit confused about what to do here.  If we pass in
    // the default Locale then special Locale handling might be
    // invoked.  However, the docs also say that Character.toLowerCase
    // rules here.  We go with the latter.
    return toUpperCase (null);
  }
Tom Tromey committed
1064

1065 1066 1067 1068 1069 1070 1071 1072
  /**
   * Trims all characters less than or equal to <code>'\u0020'</code>
   * (<code>' '</code>) from the beginning and end of this String. This
   * includes many, but not all, ASCII control characters, and all
   * {@link Character#whitespace(char)}.
   *
   * @return new trimmed String, or this if nothing trimmed
   */
1073
  public native String trim();
Tom Tromey committed
1074

1075 1076 1077 1078 1079
  /**
   * Returns this, as it is already a String!
   *
   * @return this
   */
1080
  public String toString()
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
  {
    return this;
  }

  /**
   * Copies the contents of this String into a character array. Subsequent
   * changes to the array do not affect the String.
   *
   * @return character array copying the String
   */
1091
  public native char[] toCharArray();
1092 1093 1094 1095 1096 1097 1098 1099 1100

  /**
   * Returns a String representation of an Object. This is "null" if the
   * object is null, otherwise it is <code>obj.toString()</code> (which
   * can be null).
   *
   * @param obj the Object
   * @return the string conversion of obj
   */
1101
  public static String valueOf(Object obj)
Tom Tromey committed
1102 1103 1104 1105
  {
    return obj == null ? "null" : obj.toString();
  }

1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
  /**
   * Returns a String representation of a character array. Subsequent
   * changes to the array do not affect the String.
   *
   * @param data the character array
   * @return a String containing the same character sequence as data
   * @throws NullPointerException if data is null
   * @see #valueOf(char[], int, int)
   * @see #String(char[])
   */
1116
  public static String valueOf(char[] data)
Tom Tromey committed
1117 1118 1119 1120
  {
    return valueOf (data, 0, data.length);
  }

1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
  /**
   * Returns a String representing the character sequence of the char array,
   * starting at the specified offset, and copying chars up to the specified
   * count. Subsequent changes to the array do not affect the String.
   *
   * @param data character array
   * @param offset position (base 0) to start copying out of data
   * @param count the number of characters from data to copy
   * @return String containing the chars from data[offset..offset+count]
   * @throws NullPointerException if data is null
   * @throws IndexOutOfBoundsException if (offset &lt; 0 || count &lt; 0
1132
   *         || offset + count &gt; data.length)
1133 1134 1135
   *         (while unspecified, this is a StringIndexOutOfBoundsException)
   * @see #String(char[], int, int)
   */
1136
  public static native String valueOf(char[] data, int offset, int count);
Tom Tromey committed
1137

1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
  /**
   * Returns a String representing the character sequence of the char array,
   * starting at the specified offset, and copying chars up to the specified
   * count. Subsequent changes to the array do not affect the String.
   *
   * @param data character array
   * @param offset position (base 0) to start copying out of data
   * @param count the number of characters from data to copy
   * @return String containing the chars from data[offset..offset+count]
   * @throws NullPointerException if data is null
   * @throws IndexOutOfBoundsException if (offset &lt; 0 || count &lt; 0
1149
   *         || offset + count &gt; data.length)
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
   *         (while unspecified, this is a StringIndexOutOfBoundsException)
   * @see #String(char[], int, int)
   */
  public static String copyValueOf(char[] data, int offset, int count)
  {
    String r = new String ();
    r.init(data, offset, count, false);
    return r;
  }

  /**
   * Returns a String representation of a character array. Subsequent
   * changes to the array do not affect the String.
   *
   * @param data the character array
   * @return a String containing the same character sequence as data
   * @throws NullPointerException if data is null
   * @see #copyValueOf(char[], int, int)
   * @see #String(char[])
   */
  public static String copyValueOf(char[] data)
  {
    return copyValueOf (data, 0, data.length);
  }

  /**
   * Returns a String representing a boolean.
   *
   * @param b the boolean
   * @return "true" if b is true, else "false"
   */
1181
  public static String valueOf(boolean b)
Tom Tromey committed
1182 1183 1184 1185
  {
    return b ? "true" : "false";
  }

1186 1187 1188 1189 1190 1191
  /**
   * Returns a String representing a character.
   *
   * @param c the character
   * @return String containing the single character c
   */
1192
  public static native String valueOf(char c);
Tom Tromey committed
1193

1194 1195 1196 1197 1198 1199 1200
  /**
   * Returns a String representing an integer.
   *
   * @param i the integer
   * @return String containing the integer in base 10
   * @see Integer#toString(int)
   */
1201
  public static native String valueOf(int i);
Tom Tromey committed
1202

1203 1204 1205 1206 1207 1208 1209
  /**
   * Returns a String representing a long.
   *
   * @param l the long
   * @return String containing the long in base 10
   * @see Long#toString(long)
   */
1210
  public static String valueOf(long l)
Tom Tromey committed
1211 1212 1213 1214
  {
    return Long.toString(l);
  }

1215 1216 1217 1218 1219 1220 1221
  /**
   * Returns a String representing a float.
   *
   * @param f the float
   * @return String containing the float
   * @see Float#toString(float)
   */
1222
  public static String valueOf(float f)
Tom Tromey committed
1223 1224 1225 1226
  {
    return Float.toString(f);
  }

1227 1228 1229 1230 1231 1232 1233
  /**
   * Returns a String representing a double.
   *
   * @param d the double
   * @return String containing the double
   * @see Double#toString(double)
   */
1234
  public static String valueOf(double d)
Tom Tromey committed
1235 1236 1237 1238
  {
    return Double.toString(d);
  }

1239 1240 1241 1242 1243 1244 1245 1246 1247
  /**
   * Fetches this String from the intern hashtable. If two Strings are
   * considered equal, by the equals() method, then intern() will return the
   * same String instance. ie. if (s1.equals(s2)) then
   * (s1.intern() == s2.intern()). All string literals and string-valued
   * constant expressions are already interned.
   *
   * @return the interned String
   */
1248
  public native String intern();
Tom Tromey committed
1249

1250

1251 1252 1253 1254
  private native void init(char[] chars, int offset, int count,
			   boolean dont_copy);
  private native void init(byte[] chars, int hibyte, int offset, int count);
  private native void init(byte[] chars, int offset, int count, String enc)
Tom Tromey committed
1255
    throws UnsupportedEncodingException;
1256
  private native void init(gnu.gcj.runtime.StringBuffer buffer);
1257
  private static native void rehash();
Tom Tromey committed
1258
}