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