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