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