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