String.java 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458
  1. /* String.java -- immutable character sequences; the object of string literals
  2. Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007
  3. Free Software Foundation, Inc.
  4. This file is part of GNU Classpath.
  5. GNU Classpath is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2, or (at your option)
  8. any later version.
  9. GNU Classpath is distributed in the hope that it will be useful, but
  10. WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with GNU Classpath; see the file COPYING. If not, write to the
  15. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  16. 02110-1301 USA.
  17. Linking this library statically or dynamically with other modules is
  18. making a combined work based on this library. Thus, the terms and
  19. conditions of the GNU General Public License cover the whole
  20. combination.
  21. As a special exception, the copyright holders of this library give you
  22. permission to link this library with independent modules to produce an
  23. executable, regardless of the license terms of these independent
  24. modules, and to copy and distribute the resulting executable under
  25. terms of your choice, provided that you also meet, for each linked
  26. independent module, the terms and conditions of the license of that
  27. module. An independent module is a module which is not derived from
  28. or based on this library. If you modify this library, you may extend
  29. this exception to your version of the library, but you are not
  30. obligated to do so. If you do not wish to do so, delete this
  31. exception statement from your version. */
  32. package java.lang;
  33. import java.io.Serializable;
  34. import java.io.UnsupportedEncodingException;
  35. import java.util.Comparator;
  36. import java.text.Collator;
  37. import java.util.Formatter;
  38. import java.util.Locale;
  39. import java.util.regex.Matcher;
  40. import java.util.regex.Pattern;
  41. import java.util.regex.PatternSyntaxException;
  42. /**
  43. * Strings represent an immutable set of characters. All String literals
  44. * are instances of this class, and two string literals with the same contents
  45. * refer to the same String object.
  46. *
  47. * <p>This class also includes a number of methods for manipulating the
  48. * contents of strings (of course, creating a new object if there are any
  49. * changes, as String is immutable). Case mapping relies on Unicode 3.0.0
  50. * standards, where some character sequences have a different number of
  51. * characters in the uppercase version than the lower case.
  52. *
  53. * <p>Strings are special, in that they are the only object with an overloaded
  54. * operator. When you use '+' with at least one String argument, both
  55. * arguments have String conversion performed on them, and another String (not
  56. * guaranteed to be unique) results.
  57. *
  58. * <p>String is special-cased when doing data serialization - rather than
  59. * listing the fields of this class, a String object is converted to a string
  60. * literal in the object stream.
  61. *
  62. * @author Paul N. Fisher
  63. * @author Eric Blake (ebb9@email.byu.edu)
  64. * @author Per Bothner (bothner@cygnus.com)
  65. * @author Tom Tromey (tromey@redhat.com)
  66. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  67. * @since 1.0
  68. * @status updated to 1.4
  69. */
  70. public final class String
  71. implements Serializable, Comparable<String>, CharSequence
  72. {
  73. // WARNING: String is a CORE class in the bootstrap cycle. See the comments
  74. // in vm/reference/java/lang/Runtime for implications of this fact.
  75. /**
  76. * This is probably not necessary because this class is special cased already
  77. * but it will avoid showing up as a discrepancy when comparing SUIDs.
  78. */
  79. private static final long serialVersionUID = -6849794470754667710L;
  80. /**
  81. * This is the object that holds the characters that make up the
  82. * String. It might be a char[], or it could be String. It could
  83. * even be `this'. The actual characters can't be located using
  84. * pure Java code.
  85. * @see #boffset
  86. */
  87. private Object data;
  88. /**
  89. * This is a <emph>byte</emph> offset of the actual characters from
  90. * the start of the character-holding object. Don't use this field
  91. * in Java code.
  92. */
  93. private int boffset;
  94. /**
  95. * Holds the number of characters in value. Package visible for use
  96. * by trusted code.
  97. */
  98. int count;
  99. /**
  100. * Caches the result of hashCode(). If this value is zero, the hashcode
  101. * is considered uncached (even if 0 is the correct hash value).
  102. */
  103. private int cachedHashCode;
  104. /**
  105. * An implementation for {@link #CASE_INSENSITIVE_ORDER}.
  106. * This must be {@link Serializable}. The class name is dictated by
  107. * compatibility with Sun's JDK.
  108. */
  109. private static final class CaseInsensitiveComparator
  110. implements Comparator<String>, Serializable
  111. {
  112. /**
  113. * Compatible with JDK 1.2.
  114. */
  115. private static final long serialVersionUID = 8575799808933029326L;
  116. /**
  117. * The default private constructor generates unnecessary overhead.
  118. */
  119. CaseInsensitiveComparator() {}
  120. /**
  121. * Compares to Strings, using
  122. * <code>String.compareToIgnoreCase(String)</code>.
  123. *
  124. * @param o1 the first string
  125. * @param o2 the second string
  126. * @return &lt; 0, 0, or &gt; 0 depending on the case-insensitive
  127. * comparison of the two strings.
  128. * @throws NullPointerException if either argument is null
  129. * @throws ClassCastException if either argument is not a String
  130. * @see #compareToIgnoreCase(String)
  131. */
  132. public int compare(String o1, String o2)
  133. {
  134. return o1.compareToIgnoreCase(o2);
  135. }
  136. } // class CaseInsensitiveComparator
  137. /**
  138. * A Comparator that uses <code>String.compareToIgnoreCase(String)</code>.
  139. * This comparator is {@link Serializable}. Note that it ignores Locale,
  140. * for that, you want a Collator.
  141. *
  142. * @see Collator#compare(String, String)
  143. * @since 1.2
  144. */
  145. public static final Comparator<String> CASE_INSENSITIVE_ORDER
  146. = new CaseInsensitiveComparator();
  147. /**
  148. * Creates an empty String (length 0). Unless you really need a new object,
  149. * consider using <code>""</code> instead.
  150. */
  151. public String()
  152. {
  153. data = "".data;
  154. boffset = 0;
  155. count = 0;
  156. }
  157. /**
  158. * Copies the contents of a String to a new String. Since Strings are
  159. * immutable, only a shallow copy is performed.
  160. *
  161. * @param str String to copy
  162. * @throws NullPointerException if value is null
  163. */
  164. public String(String str)
  165. {
  166. data = str.data;
  167. boffset = str.boffset;
  168. count = str.count;
  169. cachedHashCode = str.cachedHashCode;
  170. }
  171. /**
  172. * Creates a new String using the character sequence of the char array.
  173. * Subsequent changes to data do not affect the String.
  174. *
  175. * @param data char array to copy
  176. * @throws NullPointerException if data is null
  177. */
  178. public String(char[] data)
  179. {
  180. init(data, 0, data.length, false);
  181. }
  182. /**
  183. * Creates a new String using the character sequence of a subarray of
  184. * characters. The string starts at offset, and copies count chars.
  185. * Subsequent changes to data do not affect the String.
  186. *
  187. * @param data char array to copy
  188. * @param offset position (base 0) to start copying out of data
  189. * @param count the number of characters from data to copy
  190. * @throws NullPointerException if data is null
  191. * @throws IndexOutOfBoundsException if (offset &lt; 0 || count &lt; 0
  192. * || offset + count &lt; 0 (overflow)
  193. * || offset + count &gt; data.length)
  194. * (while unspecified, this is a StringIndexOutOfBoundsException)
  195. */
  196. public String(char[] data, int offset, int count)
  197. {
  198. init(data, offset, count, false);
  199. }
  200. /**
  201. * Creates a new String using an 8-bit array of integer values, starting at
  202. * an offset, and copying up to the count. Each character c, using
  203. * corresponding byte b, is created in the new String as if by performing:
  204. *
  205. * <pre>
  206. * c = (char) (((hibyte &amp; 0xff) &lt;&lt; 8) | (b &amp; 0xff))
  207. * </pre>
  208. *
  209. * @param ascii array of integer values
  210. * @param hibyte top byte of each Unicode character
  211. * @param offset position (base 0) to start copying out of ascii
  212. * @param count the number of characters from ascii to copy
  213. * @throws NullPointerException if ascii is null
  214. * @throws IndexOutOfBoundsException if (offset &lt; 0 || count &lt; 0
  215. * || offset + count &lt; 0 (overflow)
  216. * || offset + count &gt; ascii.length)
  217. * (while unspecified, this is a StringIndexOutOfBoundsException)
  218. * @see #String(byte[])
  219. * @see #String(byte[], String)
  220. * @see #String(byte[], int, int)
  221. * @see #String(byte[], int, int, String)
  222. * @deprecated use {@link #String(byte[], int, int, String)} to perform
  223. * correct encoding
  224. */
  225. public String(byte[] ascii, int hibyte, int offset, int count)
  226. {
  227. init(ascii, hibyte, offset, count);
  228. }
  229. /**
  230. * Creates a new String using an 8-bit array of integer values. Each
  231. * character c, using corresponding byte b, is created in the new String
  232. * as if by performing:
  233. *
  234. * <pre>
  235. * c = (char) (((hibyte &amp; 0xff) &lt;&lt; 8) | (b &amp; 0xff))
  236. * </pre>
  237. *
  238. * @param ascii array of integer values
  239. * @param hibyte top byte of each Unicode character
  240. * @throws NullPointerException if ascii is null
  241. * @see #String(byte[])
  242. * @see #String(byte[], String)
  243. * @see #String(byte[], int, int)
  244. * @see #String(byte[], int, int, String)
  245. * @see #String(byte[], int, int, int)
  246. * @deprecated use {@link #String(byte[], String)} to perform
  247. * correct encoding
  248. */
  249. public String(byte[] ascii, int hibyte)
  250. {
  251. init(ascii, hibyte, 0, ascii.length);
  252. }
  253. /**
  254. * Creates a new String using the portion of the byte array starting at the
  255. * offset and ending at offset + count. Uses the specified encoding type
  256. * to decode the byte array, so the resulting string may be longer or
  257. * shorter than the byte array. For more decoding control, use
  258. * {@link java.nio.charset.CharsetDecoder}, and for valid character sets,
  259. * see {@link java.nio.charset.Charset}. The behavior is not specified if
  260. * the decoder encounters invalid characters; this implementation throws
  261. * an Error.
  262. *
  263. * @param data byte array to copy
  264. * @param offset the offset to start at
  265. * @param count the number of bytes in the array to use
  266. * @param encoding the name of the encoding to use
  267. * @throws NullPointerException if data or encoding is null
  268. * @throws IndexOutOfBoundsException if offset or count is incorrect
  269. * (while unspecified, this is a StringIndexOutOfBoundsException)
  270. * @throws UnsupportedEncodingException if encoding is not found
  271. * @throws Error if the decoding fails
  272. * @since 1.1
  273. */
  274. public String(byte[] data, int offset, int count, String encoding)
  275. throws UnsupportedEncodingException
  276. {
  277. init (data, offset, count, encoding);
  278. }
  279. /**
  280. * Creates a new String using the byte array. Uses the specified encoding
  281. * type to decode the byte array, so the resulting string may be longer or
  282. * shorter than the byte array. For more decoding control, use
  283. * {@link java.nio.charset.CharsetDecoder}, and for valid character sets,
  284. * see {@link java.nio.charset.Charset}. The behavior is not specified if
  285. * the decoder encounters invalid characters; this implementation throws
  286. * an Error.
  287. *
  288. * @param data byte array to copy
  289. * @param encoding the name of the encoding to use
  290. * @throws NullPointerException if data or encoding is null
  291. * @throws UnsupportedEncodingException if encoding is not found
  292. * @throws Error if the decoding fails
  293. * @see #String(byte[], int, int, String)
  294. * @since 1.1
  295. */
  296. public String(byte[] data, String encoding)
  297. throws UnsupportedEncodingException
  298. {
  299. this(data, 0, data.length, encoding);
  300. }
  301. /**
  302. * Creates a new String using the portion of the byte array starting at the
  303. * offset and ending at offset + count. Uses the encoding of the platform's
  304. * default charset, so the resulting string may be longer or shorter than
  305. * the byte array. For more decoding control, use
  306. * {@link java.nio.charset.CharsetDecoder}. The behavior is not specified
  307. * if the decoder encounters invalid characters; this implementation throws
  308. * an Error.
  309. *
  310. * @param data byte array to copy
  311. * @param offset the offset to start at
  312. * @param count the number of bytes in the array to use
  313. * @throws NullPointerException if data is null
  314. * @throws IndexOutOfBoundsException if offset or count is incorrect
  315. * @throws Error if the decoding fails
  316. * @see #String(byte[], int, int, String)
  317. * @since 1.1
  318. */
  319. public String(byte[] data, int offset, int count)
  320. {
  321. try
  322. {
  323. init (data, offset, count,
  324. System.getProperty("file.encoding", "8859_1"));
  325. }
  326. catch (UnsupportedEncodingException x1)
  327. {
  328. // Maybe the default encoding is bad.
  329. try
  330. {
  331. init (data, offset, count, "8859_1");
  332. }
  333. catch (UnsupportedEncodingException x2)
  334. {
  335. // We know this can't happen.
  336. }
  337. }
  338. }
  339. /**
  340. * Creates a new String using the byte array. Uses the encoding of the
  341. * platform's default charset, so the resulting string may be longer or
  342. * shorter than the byte array. For more decoding control, use
  343. * {@link java.nio.charset.CharsetDecoder}. The behavior is not specified
  344. * if the decoder encounters invalid characters; this implementation throws
  345. * an Error.
  346. *
  347. * @param data byte array to copy
  348. * @throws NullPointerException if data is null
  349. * @throws Error if the decoding fails
  350. * @see #String(byte[], int, int)
  351. * @see #String(byte[], int, int, String)
  352. * @since 1.1
  353. */
  354. public String(byte[] data)
  355. {
  356. this(data, 0, data.length);
  357. }
  358. /**
  359. * Creates a new String using the character sequence represented by
  360. * the StringBuffer. Subsequent changes to buf do not affect the String.
  361. *
  362. * @param buffer StringBuffer to copy
  363. * @throws NullPointerException if buffer is null
  364. */
  365. public String(StringBuffer buffer)
  366. {
  367. synchronized (buffer)
  368. {
  369. // Share unless buffer is 3/4 empty.
  370. boolean should_copy = ((buffer.count << 2) < buffer.value.length);
  371. if (! should_copy)
  372. buffer.shared = true;
  373. init (buffer.value, 0, buffer.count, ! should_copy);
  374. }
  375. }
  376. /**
  377. * Creates a new String using the character sequence represented by
  378. * the StringBuilder. Subsequent changes to buf do not affect the String.
  379. *
  380. * @param buffer StringBuilder to copy
  381. * @throws NullPointerException if buffer is null
  382. */
  383. public String(StringBuilder buffer)
  384. {
  385. this(buffer.value, 0, buffer.count);
  386. }
  387. /**
  388. * Special constructor which can share an array when safe to do so.
  389. *
  390. * @param data the characters to copy
  391. * @param offset the location to start from
  392. * @param count the number of characters to use
  393. * @param dont_copy true if the array is trusted, and need not be copied
  394. * @throws NullPointerException if chars is null
  395. * @throws StringIndexOutOfBoundsException if bounds check fails
  396. */
  397. String(char[] data, int offset, int count, boolean dont_copy)
  398. {
  399. init(data, offset, count, dont_copy);
  400. }
  401. // This is used by gnu.gcj.runtime.StringBuffer, so it must have
  402. // package-private protection. It is accessed via CNI and so avoids
  403. // ordinary protection mechanisms.
  404. String(gnu.gcj.runtime.StringBuffer buffer)
  405. {
  406. // No need to synchronize or mark the buffer, since we know it is
  407. // only used once.
  408. init (buffer);
  409. }
  410. /**
  411. * Returns the number of characters contained in this String.
  412. *
  413. * @return the length of this String
  414. */
  415. public int length()
  416. {
  417. return count;
  418. }
  419. /**
  420. * Returns the character located at the specified index within this String.
  421. *
  422. * @param index position of character to return (base 0)
  423. * @return character located at position index
  424. * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt;= length()
  425. * (while unspecified, this is a StringIndexOutOfBoundsException)
  426. */
  427. public native char charAt(int index);
  428. /**
  429. * Get the code point at the specified index. This is like #charAt(int),
  430. * but if the character is the start of a surrogate pair, and the
  431. * following character completes the pair, then the corresponding
  432. * supplementary code point is returned.
  433. * @param index the index of the codepoint to get, starting at 0
  434. * @return the codepoint at the specified index
  435. * @throws IndexOutOfBoundsException if index is negative or &gt;= length()
  436. * @since 1.5
  437. */
  438. public synchronized int codePointAt(int index)
  439. {
  440. // Use the CharSequence overload as we get better range checking
  441. // this way.
  442. return Character.codePointAt(this, index);
  443. }
  444. /**
  445. * Get the code point before the specified index. This is like
  446. * #codePointAt(int), but checks the characters at <code>index-1</code> and
  447. * <code>index-2</code> to see if they form a supplementary code point.
  448. * @param index the index just past the codepoint to get, starting at 0
  449. * @return the codepoint at the specified index
  450. * @throws IndexOutOfBoundsException if index is negative or &gt;= length()
  451. * (while unspecified, this is a StringIndexOutOfBoundsException)
  452. * @since 1.5
  453. */
  454. public synchronized int codePointBefore(int index)
  455. {
  456. // Use the CharSequence overload as we get better range checking
  457. // this way.
  458. return Character.codePointBefore(this, index);
  459. }
  460. /**
  461. * Copies characters from this String starting at a specified start index,
  462. * ending at a specified stop index, to a character array starting at
  463. * a specified destination begin index.
  464. *
  465. * @param srcBegin index to begin copying characters from this String
  466. * @param srcEnd index after the last character to be copied from this String
  467. * @param dst character array which this String is copied into
  468. * @param dstBegin index to start writing characters into dst
  469. * @throws NullPointerException if dst is null
  470. * @throws IndexOutOfBoundsException if any indices are out of bounds
  471. * (while unspecified, source problems cause a
  472. * StringIndexOutOfBoundsException, and dst problems cause an
  473. * ArrayIndexOutOfBoundsException)
  474. */
  475. public native void getChars(int srcBegin, int srcEnd,
  476. char[] dst, int dstBegin);
  477. /**
  478. * Copies the low byte of each character from this String starting at a
  479. * specified start index, ending at a specified stop index, to a byte array
  480. * starting at a specified destination begin index.
  481. *
  482. * @param srcBegin index to being copying characters from this String
  483. * @param srcEnd index after the last character to be copied from this String
  484. * @param dst byte array which each low byte of this String is copied into
  485. * @param dstBegin index to start writing characters into dst
  486. * @throws NullPointerException if dst is null and copy length is non-zero
  487. * @throws IndexOutOfBoundsException if any indices are out of bounds
  488. * (while unspecified, source problems cause a
  489. * StringIndexOutOfBoundsException, and dst problems cause an
  490. * ArrayIndexOutOfBoundsException)
  491. * @see #getBytes()
  492. * @see #getBytes(String)
  493. * @deprecated use {@link #getBytes()}, which uses a char to byte encoder
  494. */
  495. public native void getBytes(int srcBegin, int srcEnd,
  496. byte[] dst, int dstBegin);
  497. /**
  498. * Converts the Unicode characters in this String to a byte array. Uses the
  499. * specified encoding method, so the result may be longer or shorter than
  500. * the String. For more encoding control, use
  501. * {@link java.nio.charset.CharsetEncoder}, and for valid character sets,
  502. * see {@link java.nio.charset.Charset}. The behavior is not specified if
  503. * the encoder encounters a problem; this implementation returns null.
  504. *
  505. * @param enc encoding name
  506. * @return the resulting byte array, or null on a problem
  507. * @throws NullPointerException if enc is null
  508. * @throws UnsupportedEncodingException if encoding is not supported
  509. * @since 1.1
  510. */
  511. public native byte[] getBytes(String enc)
  512. throws UnsupportedEncodingException;
  513. /**
  514. * Converts the Unicode characters in this String to a byte array. Uses the
  515. * encoding of the platform's default charset, so the result may be longer
  516. * or shorter than the String. For more encoding control, use
  517. * {@link java.nio.charset.CharsetEncoder}. The behavior is not specified if
  518. * the encoder encounters a problem; this implementation returns null.
  519. *
  520. * @return the resulting byte array, or null on a problem
  521. * @since 1.1
  522. */
  523. public byte[] getBytes()
  524. {
  525. try
  526. {
  527. return getBytes (System.getProperty("file.encoding", "8859_1"));
  528. }
  529. catch (UnsupportedEncodingException x)
  530. {
  531. // This probably shouldn't happen, but could if file.encoding
  532. // is somehow changed to a value we don't understand.
  533. try
  534. {
  535. return getBytes ("8859_1");
  536. }
  537. catch (UnsupportedEncodingException x2)
  538. {
  539. // This really shouldn't happen, because the 8859_1
  540. // encoding should always be available.
  541. throw new InternalError ("couldn't find 8859_1 encoder");
  542. }
  543. }
  544. }
  545. /**
  546. * Predicate which compares anObject to this. This is true only for Strings
  547. * with the same character sequence.
  548. *
  549. * @param anObject the object to compare
  550. * @return true if anObject is semantically equal to this
  551. * @see #compareTo(String)
  552. * @see #equalsIgnoreCase(String)
  553. */
  554. public native boolean equals(Object anObject);
  555. /**
  556. * Compares the given StringBuffer to this String. This is true if the
  557. * StringBuffer has the same content as this String at this moment.
  558. *
  559. * @param buffer the StringBuffer to compare to
  560. * @return true if StringBuffer has the same character sequence
  561. * @throws NullPointerException if the given StringBuffer is null
  562. * @since 1.4
  563. */
  564. public native boolean contentEquals(StringBuffer buffer);
  565. /**
  566. * Compares the given CharSequence to this String. This is true if
  567. * the CharSequence has the same content as this String at this
  568. * moment.
  569. *
  570. * @param seq the CharSequence to compare to
  571. * @return true if CharSequence has the same character sequence
  572. * @throws NullPointerException if the given CharSequence is null
  573. * @since 1.5
  574. */
  575. public native boolean contentEquals(CharSequence seq);
  576. /**
  577. * Compares a String to this String, ignoring case. This does not handle
  578. * multi-character capitalization exceptions; instead the comparison is
  579. * made on a character-by-character basis, and is true if:<br><ul>
  580. * <li><code>c1 == c2</code></li>
  581. * <li><code>Character.toUpperCase(c1)
  582. * == Character.toUpperCase(c2)</code></li>
  583. * <li><code>Character.toLowerCase(c1)
  584. * == Character.toLowerCase(c2)</code></li>
  585. * </ul>
  586. *
  587. * @param anotherString String to compare to this String
  588. * @return true if anotherString is equal, ignoring case
  589. * @see #equals(Object)
  590. * @see Character#toUpperCase(char)
  591. * @see Character#toLowerCase(char)
  592. */
  593. public native boolean equalsIgnoreCase(String anotherString);
  594. /**
  595. * Compares this String and another String (case sensitive,
  596. * lexicographically). The result is less than 0 if this string sorts
  597. * before the other, 0 if they are equal, and greater than 0 otherwise.
  598. * After any common starting sequence is skipped, the result is
  599. * <code>this.charAt(k) - anotherString.charAt(k)</code> if both strings
  600. * have characters remaining, or
  601. * <code>this.length() - anotherString.length()</code> if one string is
  602. * a subsequence of the other.
  603. *
  604. * @param anotherString the String to compare against
  605. * @return the comparison
  606. * @throws NullPointerException if anotherString is null
  607. */
  608. public int compareTo(String anotherString)
  609. {
  610. return nativeCompareTo(anotherString);
  611. }
  612. /**
  613. * The native implementation of compareTo(). Must be named different
  614. * since cni doesn't understand the bridge method generated from
  615. * the compareTo() method because of the Comparable<String> interface.
  616. */
  617. private native int nativeCompareTo(String anotherString);
  618. /**
  619. * Compares this String and another String (case insensitive). This
  620. * comparison is <em>similar</em> to equalsIgnoreCase, in that it ignores
  621. * locale and multi-characater capitalization, and compares characters
  622. * after performing
  623. * <code>Character.toLowerCase(Character.toUpperCase(c))</code> on each
  624. * character of the string. This is unsatisfactory for locale-based
  625. * comparison, in which case you should use {@link java.text.Collator}.
  626. *
  627. * @param str the string to compare against
  628. * @return the comparison
  629. * @see Collator#compare(String, String)
  630. * @since 1.2
  631. */
  632. public int compareToIgnoreCase(String str)
  633. {
  634. return this.toUpperCase().toLowerCase().compareTo(
  635. str.toUpperCase().toLowerCase());
  636. }
  637. /**
  638. * Predicate which determines if this String matches another String
  639. * starting at a specified offset for each String and continuing
  640. * for a specified length. Indices out of bounds are harmless, and give
  641. * a false result.
  642. *
  643. * @param toffset index to start comparison at for this String
  644. * @param other String to compare region to this String
  645. * @param ooffset index to start comparison at for other
  646. * @param len number of characters to compare
  647. * @return true if regions match (case sensitive)
  648. * @throws NullPointerException if other is null
  649. */
  650. public native boolean regionMatches(int toffset,
  651. String other, int ooffset, int len);
  652. /**
  653. * Predicate which determines if this String matches another String
  654. * starting at a specified offset for each String and continuing
  655. * for a specified length, optionally ignoring case. Indices out of bounds
  656. * are harmless, and give a false result. Case comparisons are based on
  657. * <code>Character.toLowerCase()</code> and
  658. * <code>Character.toUpperCase()</code>, not on multi-character
  659. * capitalization expansions.
  660. *
  661. * @param ignoreCase true if case should be ignored in comparision
  662. * @param toffset index to start comparison at for this String
  663. * @param other String to compare region to this String
  664. * @param ooffset index to start comparison at for other
  665. * @param len number of characters to compare
  666. * @return true if regions match, false otherwise
  667. * @throws NullPointerException if other is null
  668. */
  669. public native boolean regionMatches(boolean ignoreCase, int toffset,
  670. String other, int ooffset, int len);
  671. /**
  672. * Predicate which determines if this String contains the given prefix,
  673. * beginning comparison at toffset. The result is false if toffset is
  674. * negative or greater than this.length(), otherwise it is the same as
  675. * <code>this.substring(toffset).startsWith(prefix)</code>.
  676. *
  677. * @param prefix String to compare
  678. * @param toffset offset for this String where comparison starts
  679. * @return true if this String starts with prefix
  680. * @throws NullPointerException if prefix is null
  681. * @see #regionMatches(boolean, int, String, int, int)
  682. */
  683. public native boolean startsWith(String prefix, int toffset);
  684. /**
  685. * Predicate which determines if this String starts with a given prefix.
  686. * If the prefix is an empty String, true is returned.
  687. *
  688. * @param prefix String to compare
  689. * @return true if this String starts with the prefix
  690. * @throws NullPointerException if prefix is null
  691. * @see #startsWith(String, int)
  692. */
  693. public boolean startsWith(String prefix)
  694. {
  695. return startsWith (prefix, 0);
  696. }
  697. /**
  698. * Predicate which determines if this String ends with a given suffix.
  699. * If the suffix is an empty String, true is returned.
  700. *
  701. * @param suffix String to compare
  702. * @return true if this String ends with the suffix
  703. * @throws NullPointerException if suffix is null
  704. * @see #regionMatches(boolean, int, String, int, int)
  705. */
  706. public boolean endsWith(String suffix)
  707. {
  708. return regionMatches (this.count - suffix.count, suffix, 0, suffix.count);
  709. }
  710. /**
  711. * Computes the hashcode for this String. This is done with int arithmetic,
  712. * where ** represents exponentiation, by this formula:<br>
  713. * <code>s[0]*31**(n-1) + s[1]*31**(n-2) + ... + s[n-1]</code>.
  714. *
  715. * @return hashcode value of this String
  716. */
  717. public native int hashCode();
  718. /**
  719. * Finds the first instance of a character in this String.
  720. *
  721. * @param ch character to find
  722. * @return location (base 0) of the character, or -1 if not found
  723. */
  724. public int indexOf(int ch)
  725. {
  726. return indexOf(ch, 0);
  727. }
  728. /**
  729. * Finds the first instance of a character in this String, starting at
  730. * a given index. If starting index is less than 0, the search
  731. * starts at the beginning of this String. If the starting index
  732. * is greater than the length of this String, -1 is returned.
  733. *
  734. * @param ch character to find
  735. * @param fromIndex index to start the search
  736. * @return location (base 0) of the character, or -1 if not found
  737. */
  738. public native int indexOf(int ch, int fromIndex);
  739. /**
  740. * Finds the last instance of a character in this String.
  741. *
  742. * @param ch character to find
  743. * @return location (base 0) of the character, or -1 if not found
  744. */
  745. public int lastIndexOf(int ch)
  746. {
  747. return lastIndexOf(ch, count - 1);
  748. }
  749. /**
  750. * Finds the last instance of a character in this String, starting at
  751. * a given index. If starting index is greater than the maximum valid
  752. * index, then the search begins at the end of this String. If the
  753. * starting index is less than zero, -1 is returned.
  754. *
  755. * @param ch character to find
  756. * @param fromIndex index to start the search
  757. * @return location (base 0) of the character, or -1 if not found
  758. */
  759. public native int lastIndexOf(int ch, int fromIndex);
  760. /**
  761. * Finds the first instance of a String in this String.
  762. *
  763. * @param str String to find
  764. * @return location (base 0) of the String, or -1 if not found
  765. * @throws NullPointerException if str is null
  766. */
  767. public int indexOf(String str)
  768. {
  769. return indexOf(str, 0);
  770. }
  771. /**
  772. * Finds the first instance of a String in this String, starting at
  773. * a given index. If starting index is less than 0, the search
  774. * starts at the beginning of this String. If the starting index
  775. * is greater than the length of this String, -1 is returned.
  776. *
  777. * @param str String to find
  778. * @param fromIndex index to start the search
  779. * @return location (base 0) of the String, or -1 if not found
  780. * @throws NullPointerException if str is null
  781. */
  782. public native int indexOf(String str, int fromIndex);
  783. /**
  784. * Finds the last instance of a String in this String.
  785. *
  786. * @param str String to find
  787. * @return location (base 0) of the String, or -1 if not found
  788. * @throws NullPointerException if str is null
  789. */
  790. public int lastIndexOf(String str)
  791. {
  792. return lastIndexOf(str, count - str.count);
  793. }
  794. /**
  795. * Finds the last instance of a String in this String, starting at
  796. * a given index. If starting index is greater than the maximum valid
  797. * index, then the search begins at the end of this String. If the
  798. * starting index is less than zero, -1 is returned.
  799. *
  800. * @param str String to find
  801. * @param fromIndex index to start the search
  802. * @return location (base 0) of the String, or -1 if not found
  803. * @throws NullPointerException if str is null
  804. */
  805. public int lastIndexOf(String str, int fromIndex)
  806. {
  807. if (fromIndex >= count)
  808. fromIndex = count - str.count;
  809. for (;; --fromIndex)
  810. {
  811. if (fromIndex < 0)
  812. return -1;
  813. if (startsWith(str, fromIndex))
  814. return fromIndex;
  815. }
  816. }
  817. /**
  818. * Creates a substring of this String, starting at a specified index
  819. * and ending at the end of this String.
  820. *
  821. * @param begin index to start substring (base 0)
  822. * @return new String which is a substring of this String
  823. * @throws IndexOutOfBoundsException if begin &lt; 0 || begin &gt; length()
  824. * (while unspecified, this is a StringIndexOutOfBoundsException)
  825. */
  826. public String substring(int begin)
  827. {
  828. return substring(begin, count);
  829. }
  830. /**
  831. * Creates a substring of this String, starting at a specified index
  832. * and ending at one character before a specified index.
  833. *
  834. * @param begin index to start substring (inclusive, base 0)
  835. * @param end index to end at (exclusive)
  836. * @return new String which is a substring of this String
  837. * @throws IndexOutOfBoundsException if begin &lt; 0 || end &gt; length()
  838. * || begin &gt; end (while unspecified, this is a
  839. * StringIndexOutOfBoundsException)
  840. */
  841. public native String substring(int begin, int end);
  842. /**
  843. * Creates a substring of this String, starting at a specified index
  844. * and ending at one character before a specified index. This behaves like
  845. * <code>substring(begin, end)</code>.
  846. *
  847. * @param begin index to start substring (inclusive, base 0)
  848. * @param end index to end at (exclusive)
  849. * @return new String which is a substring of this String
  850. * @throws IndexOutOfBoundsException if begin &lt; 0 || end &gt; length()
  851. * || begin &gt; end
  852. * @since 1.4
  853. */
  854. public CharSequence subSequence(int begin, int end)
  855. {
  856. return substring(begin, end);
  857. }
  858. /**
  859. * Concatenates a String to this String. This results in a new string unless
  860. * one of the two originals is "".
  861. *
  862. * @param str String to append to this String
  863. * @return newly concatenated String
  864. * @throws NullPointerException if str is null
  865. */
  866. public native String concat(String str);
  867. /**
  868. * Replaces every instance of a character in this String with a new
  869. * character. If no replacements occur, this is returned.
  870. *
  871. * @param oldChar the old character to replace
  872. * @param newChar the new character
  873. * @return new String with all instances of oldChar replaced with newChar
  874. */
  875. public native String replace(char oldChar, char newChar);
  876. /**
  877. * Test if this String matches a regular expression. This is shorthand for
  878. * <code>{@link Pattern}.matches(regex, this)</code>.
  879. *
  880. * @param regex the pattern to match
  881. * @return true if the pattern matches
  882. * @throws NullPointerException if regex is null
  883. * @throws PatternSyntaxException if regex is invalid
  884. * @see Pattern#matches(String, CharSequence)
  885. * @since 1.4
  886. */
  887. public boolean matches(String regex)
  888. {
  889. return Pattern.matches(regex, this);
  890. }
  891. /**
  892. * Replaces the first substring match of the regular expression with a
  893. * given replacement. This is shorthand for <code>{@link Pattern}
  894. * .compile(regex).matcher(this).replaceFirst(replacement)</code>.
  895. *
  896. * @param regex the pattern to match
  897. * @param replacement the replacement string
  898. * @return the modified string
  899. * @throws NullPointerException if regex or replacement is null
  900. * @throws PatternSyntaxException if regex is invalid
  901. * @see #replaceAll(String, String)
  902. * @see Pattern#compile(String)
  903. * @see Pattern#matcher(CharSequence)
  904. * @see Matcher#replaceFirst(String)
  905. * @since 1.4
  906. */
  907. public String replaceFirst(String regex, String replacement)
  908. {
  909. return Pattern.compile(regex).matcher(this).replaceFirst(replacement);
  910. }
  911. /**
  912. * Replaces all matching substrings of the regular expression with a
  913. * given replacement. This is shorthand for <code>{@link Pattern}
  914. * .compile(regex).matcher(this).replaceAll(replacement)</code>.
  915. *
  916. * @param regex the pattern to match
  917. * @param replacement the replacement string
  918. * @return the modified string
  919. * @throws NullPointerException if regex or replacement is null
  920. * @throws PatternSyntaxException if regex is invalid
  921. * @see #replaceFirst(String, String)
  922. * @see Pattern#compile(String)
  923. * @see Pattern#matcher(CharSequence)
  924. * @see Matcher#replaceAll(String)
  925. * @since 1.4
  926. */
  927. public String replaceAll(String regex, String replacement)
  928. {
  929. return Pattern.compile(regex).matcher(this).replaceAll(replacement);
  930. }
  931. /**
  932. * Split this string around the matches of a regular expression. Each
  933. * element of the returned array is the largest block of characters not
  934. * terminated by the regular expression, in the order the matches are found.
  935. *
  936. * <p>The limit affects the length of the array. If it is positive, the
  937. * array will contain at most n elements (n - 1 pattern matches). If
  938. * negative, the array length is unlimited, but there can be trailing empty
  939. * entries. if 0, the array length is unlimited, and trailing empty entries
  940. * are discarded.
  941. *
  942. * <p>For example, splitting "boo:and:foo" yields:<br>
  943. * <table border=0>
  944. * <th><td>Regex</td> <td>Limit</td> <td>Result</td></th>
  945. * <tr><td>":"</td> <td>2</td> <td>{ "boo", "and:foo" }</td></tr>
  946. * <tr><td>":"</td> <td>t</td> <td>{ "boo", "and", "foo" }</td></tr>
  947. * <tr><td>":"</td> <td>-2</td> <td>{ "boo", "and", "foo" }</td></tr>
  948. * <tr><td>"o"</td> <td>5</td> <td>{ "b", "", ":and:f", "", "" }</td></tr>
  949. * <tr><td>"o"</td> <td>-2</td> <td>{ "b", "", ":and:f", "", "" }</td></tr>
  950. * <tr><td>"o"</td> <td>0</td> <td>{ "b", "", ":and:f" }</td></tr>
  951. * </table>
  952. *
  953. * <p>This is shorthand for
  954. * <code>{@link Pattern}.compile(regex).split(this, limit)</code>.
  955. *
  956. * @param regex the pattern to match
  957. * @param limit the limit threshold
  958. * @return the array of split strings
  959. * @throws NullPointerException if regex or replacement is null
  960. * @throws PatternSyntaxException if regex is invalid
  961. * @see Pattern#compile(String)
  962. * @see Pattern#split(CharSequence, int)
  963. * @since 1.4
  964. */
  965. public String[] split(String regex, int limit)
  966. {
  967. return Pattern.compile(regex).split(this, limit);
  968. }
  969. /**
  970. * Split this string around the matches of a regular expression. Each
  971. * element of the returned array is the largest block of characters not
  972. * terminated by the regular expression, in the order the matches are found.
  973. * The array length is unlimited, and trailing empty entries are discarded,
  974. * as though calling <code>split(regex, 0)</code>.
  975. *
  976. * @param regex the pattern to match
  977. * @return the array of split strings
  978. * @throws NullPointerException if regex or replacement is null
  979. * @throws PatternSyntaxException if regex is invalid
  980. * @see #split(String, int)
  981. * @see Pattern#compile(String)
  982. * @see Pattern#split(CharSequence, int)
  983. * @since 1.4
  984. */
  985. public String[] split(String regex)
  986. {
  987. return Pattern.compile(regex).split(this, 0);
  988. }
  989. /**
  990. * Lowercases this String according to a particular locale. This uses
  991. * Unicode's special case mappings, as applied to the given Locale, so the
  992. * resulting string may be a different length.
  993. *
  994. * @param loc locale to use
  995. * @return new lowercased String, or this if no characters were lowercased
  996. * @throws NullPointerException if loc is null
  997. * @see #toUpperCase(Locale)
  998. * @since 1.1
  999. */
  1000. public native String toLowerCase(Locale locale);
  1001. /**
  1002. * Lowercases this String. This uses Unicode's special case mappings, as
  1003. * applied to the platform's default Locale, so the resulting string may
  1004. * be a different length.
  1005. *
  1006. * @return new lowercased String, or this if no characters were lowercased
  1007. * @see #toLowerCase(Locale)
  1008. * @see #toUpperCase()
  1009. */
  1010. public String toLowerCase()
  1011. {
  1012. // The JDK is a bit confused about what to do here. If we pass in
  1013. // the default Locale then special Locale handling might be
  1014. // invoked. However, the docs also say that Character.toLowerCase
  1015. // rules here. We go with the latter.
  1016. return toLowerCase (null);
  1017. }
  1018. /**
  1019. * Uppercases this String according to a particular locale. This uses
  1020. * Unicode's special case mappings, as applied to the given Locale, so the
  1021. * resulting string may be a different length.
  1022. *
  1023. * @param loc locale to use
  1024. * @return new uppercased String, or this if no characters were uppercased
  1025. * @throws NullPointerException if loc is null
  1026. * @see #toLowerCase(Locale)
  1027. * @since 1.1
  1028. */
  1029. public native String toUpperCase(Locale locale);
  1030. /**
  1031. * Uppercases this String. This uses Unicode's special case mappings, as
  1032. * applied to the platform's default Locale, so the resulting string may
  1033. * be a different length.
  1034. *
  1035. * @return new uppercased String, or this if no characters were uppercased
  1036. * @see #toUpperCase(Locale)
  1037. * @see #toLowerCase()
  1038. */
  1039. public String toUpperCase()
  1040. {
  1041. // The JDK is a bit confused about what to do here. If we pass in
  1042. // the default Locale then special Locale handling might be
  1043. // invoked. However, the docs also say that Character.toLowerCase
  1044. // rules here. We go with the latter.
  1045. return toUpperCase (null);
  1046. }
  1047. /**
  1048. * Trims all characters less than or equal to <code>'\u0020'</code>
  1049. * (<code>' '</code>) from the beginning and end of this String. This
  1050. * includes many, but not all, ASCII control characters, and all
  1051. * {@link Character#isWhitespace(char)}.
  1052. *
  1053. * @return new trimmed String, or this if nothing trimmed
  1054. */
  1055. public native String trim();
  1056. /**
  1057. * Returns this, as it is already a String!
  1058. *
  1059. * @return this
  1060. */
  1061. public String toString()
  1062. {
  1063. return this;
  1064. }
  1065. /**
  1066. * Copies the contents of this String into a character array. Subsequent
  1067. * changes to the array do not affect the String.
  1068. *
  1069. * @return character array copying the String
  1070. */
  1071. public native char[] toCharArray();
  1072. /**
  1073. * Returns a String representation of an Object. This is "null" if the
  1074. * object is null, otherwise it is <code>obj.toString()</code> (which
  1075. * can be null).
  1076. *
  1077. * @param obj the Object
  1078. * @return the string conversion of obj
  1079. */
  1080. public static String valueOf(Object obj)
  1081. {
  1082. return obj == null ? "null" : obj.toString();
  1083. }
  1084. /**
  1085. * Returns a String representation of a character array. Subsequent
  1086. * changes to the array do not affect the String.
  1087. *
  1088. * @param data the character array
  1089. * @return a String containing the same character sequence as data
  1090. * @throws NullPointerException if data is null
  1091. * @see #valueOf(char[], int, int)
  1092. * @see #String(char[])
  1093. */
  1094. public static String valueOf(char[] data)
  1095. {
  1096. return valueOf (data, 0, data.length);
  1097. }
  1098. /**
  1099. * Returns a String representing the character sequence of the char array,
  1100. * starting at the specified offset, and copying chars up to the specified
  1101. * count. Subsequent changes to the array do not affect the String.
  1102. *
  1103. * @param data character array
  1104. * @param offset position (base 0) to start copying out of data
  1105. * @param count the number of characters from data to copy
  1106. * @return String containing the chars from data[offset..offset+count]
  1107. * @throws NullPointerException if data is null
  1108. * @throws IndexOutOfBoundsException if (offset &lt; 0 || count &lt; 0
  1109. * || offset + count &gt; data.length)
  1110. * (while unspecified, this is a StringIndexOutOfBoundsException)
  1111. * @see #String(char[], int, int)
  1112. */
  1113. public static native String valueOf(char[] data, int offset, int count);
  1114. /**
  1115. * Returns a String representing the character sequence of the char array,
  1116. * starting at the specified offset, and copying chars up to the specified
  1117. * count. Subsequent changes to the array do not affect the String.
  1118. *
  1119. * @param data character array
  1120. * @param offset position (base 0) to start copying out of data
  1121. * @param count the number of characters from data to copy
  1122. * @return String containing the chars from data[offset..offset+count]
  1123. * @throws NullPointerException if data is null
  1124. * @throws IndexOutOfBoundsException if (offset &lt; 0 || count &lt; 0
  1125. * || offset + count &lt; 0 (overflow)
  1126. * || offset + count &gt; data.length)
  1127. * (while unspecified, this is a StringIndexOutOfBoundsException)
  1128. * @see #String(char[], int, int)
  1129. */
  1130. public static String copyValueOf(char[] data, int offset, int count)
  1131. {
  1132. String r = new String ();
  1133. r.init(data, offset, count, false);
  1134. return r;
  1135. }
  1136. /**
  1137. * Returns a String representation of a character array. Subsequent
  1138. * changes to the array do not affect the String.
  1139. *
  1140. * @param data the character array
  1141. * @return a String containing the same character sequence as data
  1142. * @throws NullPointerException if data is null
  1143. * @see #copyValueOf(char[], int, int)
  1144. * @see #String(char[])
  1145. */
  1146. public static String copyValueOf(char[] data)
  1147. {
  1148. return copyValueOf (data, 0, data.length);
  1149. }
  1150. /**
  1151. * Returns a String representing a boolean.
  1152. *
  1153. * @param b the boolean
  1154. * @return "true" if b is true, else "false"
  1155. */
  1156. public static String valueOf(boolean b)
  1157. {
  1158. return b ? "true" : "false";
  1159. }
  1160. /**
  1161. * Returns a String representing a character.
  1162. *
  1163. * @param c the character
  1164. * @return String containing the single character c
  1165. */
  1166. public static native String valueOf(char c);
  1167. /**
  1168. * Returns a String representing an integer.
  1169. *
  1170. * @param i the integer
  1171. * @return String containing the integer in base 10
  1172. * @see Integer#toString(int)
  1173. */
  1174. public static native String valueOf(int i);
  1175. /**
  1176. * Returns a String representing a long.
  1177. *
  1178. * @param l the long
  1179. * @return String containing the long in base 10
  1180. * @see Long#toString(long)
  1181. */
  1182. public static String valueOf(long l)
  1183. {
  1184. return Long.toString(l);
  1185. }
  1186. /**
  1187. * Returns a String representing a float.
  1188. *
  1189. * @param f the float
  1190. * @return String containing the float
  1191. * @see Float#toString(float)
  1192. */
  1193. public static String valueOf(float f)
  1194. {
  1195. return Float.toString(f);
  1196. }
  1197. /**
  1198. * Returns a String representing a double.
  1199. *
  1200. * @param d the double
  1201. * @return String containing the double
  1202. * @see Double#toString(double)
  1203. */
  1204. public static String valueOf(double d)
  1205. {
  1206. return Double.toString(d);
  1207. }
  1208. /** @since 1.5 */
  1209. public static String format(Locale locale, String format, Object... args)
  1210. {
  1211. Formatter f = new Formatter(locale);
  1212. return f.format(format, args).toString();
  1213. }
  1214. /** @since 1.5 */
  1215. public static String format(String format, Object... args)
  1216. {
  1217. return format(Locale.getDefault(), format, args);
  1218. }
  1219. /**
  1220. * Fetches this String from the intern hashtable.
  1221. * If two Strings are considered equal, by the equals() method,
  1222. * then intern() will return the same String instance. ie.
  1223. * if (s1.equals(s2)) then (s1.intern() == s2.intern()).
  1224. * All string literals and string-valued constant expressions
  1225. * are already interned.
  1226. *
  1227. * @return the interned String
  1228. */
  1229. public native String intern();
  1230. /**
  1231. * Return the number of code points between two indices in the
  1232. * <code>String</code>. An unpaired surrogate counts as a
  1233. * code point for this purpose. Characters outside the indicated
  1234. * range are not examined, even if the range ends in the middle of a
  1235. * surrogate pair.
  1236. *
  1237. * @param start the starting index
  1238. * @param end one past the ending index
  1239. * @return the number of code points
  1240. * @since 1.5
  1241. */
  1242. public synchronized int codePointCount(int start, int end)
  1243. {
  1244. if (start < 0 || end > count || start > end)
  1245. throw new StringIndexOutOfBoundsException();
  1246. int count = 0;
  1247. while (start < end)
  1248. {
  1249. char base = charAt(start);
  1250. if (base < Character.MIN_HIGH_SURROGATE
  1251. || base > Character.MAX_HIGH_SURROGATE
  1252. || start == end
  1253. || start == count
  1254. || charAt(start + 1) < Character.MIN_LOW_SURROGATE
  1255. || charAt(start + 1) > Character.MAX_LOW_SURROGATE)
  1256. {
  1257. // Nothing.
  1258. }
  1259. else
  1260. {
  1261. // Surrogate pair.
  1262. ++start;
  1263. }
  1264. ++start;
  1265. ++count;
  1266. }
  1267. return count;
  1268. }
  1269. /**
  1270. * Returns true iff this String contains the sequence of Characters
  1271. * described in s.
  1272. * @param s the CharSequence
  1273. * @return true iff this String contains s
  1274. *
  1275. * @since 1.5
  1276. */
  1277. public boolean contains (CharSequence s)
  1278. {
  1279. return this.indexOf(s.toString()) != -1;
  1280. }
  1281. /**
  1282. * Returns a string that is this string with all instances of the sequence
  1283. * represented by <code>target</code> replaced by the sequence in
  1284. * <code>replacement</code>.
  1285. * @param target the sequence to be replaced
  1286. * @param replacement the sequence used as the replacement
  1287. * @return the string constructed as above
  1288. */
  1289. public String replace (CharSequence target, CharSequence replacement)
  1290. {
  1291. String targetString = target.toString();
  1292. String replaceString = replacement.toString();
  1293. int targetLength = target.length();
  1294. int replaceLength = replacement.length();
  1295. int startPos = this.indexOf(targetString);
  1296. StringBuilder result = new StringBuilder(this);
  1297. while (startPos != -1)
  1298. {
  1299. // Replace the target with the replacement
  1300. result.replace(startPos, startPos + targetLength, replaceString);
  1301. // Search for a new occurrence of the target
  1302. startPos = result.indexOf(targetString, startPos + replaceLength);
  1303. }
  1304. return result.toString();
  1305. }
  1306. /**
  1307. * Return the index into this String that is offset from the given index by
  1308. * <code>codePointOffset</code> code points.
  1309. * @param index the index at which to start
  1310. * @param codePointOffset the number of code points to offset
  1311. * @return the index into this String that is <code>codePointOffset</code>
  1312. * code points offset from <code>index</code>.
  1313. *
  1314. * @throws IndexOutOfBoundsException if index is negative or larger than the
  1315. * length of this string.
  1316. * @throws IndexOutOfBoundsException if codePointOffset is positive and the
  1317. * substring starting with index has fewer than codePointOffset code points.
  1318. * @throws IndexOutOfBoundsException if codePointOffset is negative and the
  1319. * substring ending with index has fewer than (-codePointOffset) code points.
  1320. * @since 1.5
  1321. */
  1322. public int offsetByCodePoints(int index, int codePointOffset)
  1323. {
  1324. if (index < 0 || index > count)
  1325. throw new IndexOutOfBoundsException();
  1326. return Character.offsetByCodePoints(this, index, codePointOffset);
  1327. }
  1328. /**
  1329. * Returns true if, and only if, {@link #length()}
  1330. * is <code>0</code>.
  1331. *
  1332. * @return true if the length of the string is zero.
  1333. * @since 1.6
  1334. */
  1335. public boolean isEmpty()
  1336. {
  1337. return count == 0;
  1338. }
  1339. // Generate a String that shares the value array: subsequent changes
  1340. // to this array will affect the String. A private internal method
  1341. // that is called from CPStringBuilder by compiler-generated code.
  1342. private static String toString(char[] value, int startIndex, int count)
  1343. {
  1344. return new String(value, startIndex, count, true);
  1345. }
  1346. private native void init(char[] chars, int offset, int count,
  1347. boolean dont_copy);
  1348. private native void init(byte[] chars, int hibyte, int offset, int count);
  1349. private native void init(byte[] chars, int offset, int count, String enc)
  1350. throws UnsupportedEncodingException;
  1351. private native void init(gnu.gcj.runtime.StringBuffer buffer);
  1352. }