1. /* ====================================================================
  2. * The Apache Software License, Version 1.1
  3. *
  4. * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
  5. * reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions
  9. * are met:
  10. *
  11. * 1. Redistributions of source code must retain the above copyright
  12. * notice, this list of conditions and the following disclaimer.
  13. *
  14. * 2. Redistributions in binary form must reproduce the above copyright
  15. * notice, this list of conditions and the following disclaimer in
  16. * the documentation and/or other materials provided with the
  17. * distribution.
  18. *
  19. * 3. The end-user documentation included with the redistribution, if
  20. * any, must include the following acknowledgement:
  21. * "This product includes software developed by the
  22. * Apache Software Foundation (http://www.apache.org/)."
  23. * Alternately, this acknowledgement may appear in the software itself,
  24. * if and wherever such third-party acknowledgements normally appear.
  25. *
  26. * 4. The names "The Jakarta Project", "Commons", and "Apache Software
  27. * Foundation" must not be used to endorse or promote products derived
  28. * from this software without prior written permission. For written
  29. * permission, please contact apache@apache.org.
  30. *
  31. * 5. Products derived from this software may not be called "Apache"
  32. * nor may "Apache" appear in their names without prior written
  33. * permission of the Apache Software Foundation.
  34. *
  35. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  36. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  37. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  38. * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
  39. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  40. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  41. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  42. * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  43. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  44. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  45. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  46. * SUCH DAMAGE.
  47. * ====================================================================
  48. *
  49. * This software consists of voluntary contributions made by many
  50. * individuals on behalf of the Apache Software Foundation. For more
  51. * information on the Apache Software Foundation, please see
  52. * <http://www.apache.org/>.
  53. */
  54. package org.apache.commons.lang;
  55. import java.util.ArrayList;
  56. import java.util.Iterator;
  57. import java.util.List;
  58. /**
  59. * <p>Operations on {@link java.lang.String} that are
  60. * <code>null</code> safe.</p>
  61. *
  62. * <ul>
  63. * <li><b>IsEmpty/IsBlank</b>
  64. * - checks if a String contains text</li>
  65. * <li><b>Trim/Strip</b>
  66. * - removes leading and trailing whitespace</li>
  67. * <li><b>Equals</b>
  68. * - compares two strings null-safe</li>
  69. * <li><b>IndexOf/LastIndexOf/Contains</b>
  70. * - null-safe index-of checks
  71. * <li><b>IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut</b>
  72. * - index-of any of a set of Strings</li>
  73. * <li><b>ContainsOnly/ContainsNone</b>
  74. * - does String contains only/none of these characters</li>
  75. * <li><b>Substring/Left/Right/Mid</b>
  76. * - null-safe substring extractions</li>
  77. * <li><b>SubstringBefore/SubstringAfter/SubstringBetween</b>
  78. * - substring extraction relative to other strings</li>
  79. * <li><b>Split/Join</b>
  80. * - splits a String into an array of substrings and vice versa</li>
  81. * <li><b>Replace/Delete/Overlay</b>
  82. * - Searches a String and replaces one String with another</li>
  83. * <li><b>Chomp/Chop</b>
  84. * - removes the last part of a String</li>
  85. * <li><b>LeftPad/RightPad/Center/Repeat</b>
  86. * - pads a String</li>
  87. * <li><b>UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize</b>
  88. * - changes the case of a String</li>
  89. * <li><b>CountMatches</b>
  90. * - counts the number of occurrances of one String in another</li>
  91. * <li><b>IsAlpha/IsNumeric/IsWhitespace</b>
  92. * - checks the characters in a String</li>
  93. * <li><b>DefaultString</b>
  94. * - protects against a null input String</li>
  95. * <li><b>Reverse/ReverseDelimited</b>
  96. * - reverses a String</li>
  97. * <li><b>Abbreviate</b>
  98. * - abbreviates a string using ellipsis</li>
  99. * <li><b>Difference</b>
  100. * - compares two Strings and reports on their differences</li>
  101. * <li><b>LevensteinDistance</b>
  102. * - the number of changes needed to change one String into another</li>
  103. * </ul>
  104. *
  105. * <p>The <code>StringUtils</code> class defines certain words related to
  106. * String handling.</p>
  107. *
  108. * <ul>
  109. * <li>null - <code>null</code></li>
  110. * <li>empty - a zero-length string (<code>""</code>)</li>
  111. * <li>space - the space character (<code>' '</code>, char 32)</li>
  112. * <li>whitespace - the characters defined by {@link Character#isWhitespace(char)}</li>
  113. * <li>trim - the characters <= 32 as in {@link String#trim()}</li>
  114. * </ul>
  115. *
  116. * <p><code>StringUtils</code> handles <code>null</code> input Strings quietly.
  117. * That is to say that a <code>null</code> input will return <code>null</code>.
  118. * Where a <code>boolean</code> or <code>int</code> is being returned
  119. * details vary by method.</p>
  120. *
  121. * <p>A side effect of the <code>null</code> handling is that a
  122. * <code>NullPointerException</code> should be considered a bug in
  123. * <code>StringUtils</code> (except for deprecated methods).</p>
  124. *
  125. * <p>Methods in this class give sample code to explain their operation.
  126. * The symbol <code>*</code> is used to indicate any input including <code>null</code>.</p>
  127. *
  128. * @see java.lang.String
  129. * @author <a href="http://jakarta.apache.org/turbine/">Apache Jakarta Turbine</a>
  130. * @author GenerationJavaCore
  131. * @author <a href="mailto:jon@latchkey.com">Jon S. Stevens</a>
  132. * @author <a href="mailto:dlr@finemaltcoding.com">Daniel Rall</a>
  133. * @author <a href="mailto:gcoladonato@yahoo.com">Greg Coladonato</a>
  134. * @author <a href="mailto:bayard@generationjava.com">Henri Yandell</a>
  135. * @author <a href="mailto:ed@apache.org">Ed Korthof</a>
  136. * @author <a href="mailto:rand_mcneely@yahoo.com">Rand McNeely</a>
  137. * @author Stephen Colebourne
  138. * @author <a href="mailto:fredrik@westermarck.com">Fredrik Westermarck</a>
  139. * @author Holger Krauth
  140. * @author <a href="mailto:alex@purpletech.com">Alexander Day Chaffee</a>
  141. * @author <a href="mailto:hps@intermeta.de">Henning P. Schmiedehausen</a>
  142. * @author Arun Mammen Thomas
  143. * @author Gary Gregory
  144. * @author Phil Steitz
  145. * @since 1.0
  146. * @version $Id: StringUtils.java,v 1.107 2003/08/23 10:39:20 scolebourne Exp $
  147. */
  148. public class StringUtils {
  149. // Performance testing notes (JDK 1.4, Jul03, scolebourne)
  150. // Whitespace:
  151. // Character.isWhitespace() is faster than WHITESPACE.indexOf()
  152. // where WHITESPACE is a string of all whitespace characters
  153. //
  154. // Character access:
  155. // String.charAt(n) versus toCharArray(), then array[n]
  156. // String.charAt(n) is about 15% worse for a 10K string
  157. // They are about equal for a length 50 string
  158. // String.charAt(n) is about 4 times better for a length 3 string
  159. // String.charAt(n) is best bet overall
  160. //
  161. // Append:
  162. // String.concat about twice as fast as StringBuffer.append
  163. // (not sure who tested this)
  164. /**
  165. * The empty String <code>""</code>.
  166. * @since 2.0
  167. */
  168. public static final String EMPTY = "";
  169. /**
  170. * <p>The maximum size to which the padding constant(s) can expand.</p>
  171. */
  172. private static final int PAD_LIMIT = 8192;
  173. /**
  174. * <p>An array of <code>String</code>s used for padding.</p>
  175. *
  176. * <p>Used for efficient space padding. The length of each String expands as needed.</p>
  177. */
  178. private static final String[] PADDING = new String[Character.MAX_VALUE];
  179. static {
  180. // space padding is most common, start with 64 chars
  181. PADDING[32] = " ";
  182. }
  183. /**
  184. * <p><code>StringUtils</code> instances should NOT be constructed in
  185. * standard programming. Instead, the class should be used as
  186. * <code>StringUtils.trim(" foo ");</code>.</p>
  187. *
  188. * <p>This constructor is public to permit tools that require a JavaBean
  189. * instance to operate.</p>
  190. */
  191. public StringUtils() {
  192. }
  193. // Empty checks
  194. //-----------------------------------------------------------------------
  195. /**
  196. * <p>Checks if a String is empty ("") or null.</p>
  197. *
  198. * <pre>
  199. * StringUtils.isEmpty(null) = true
  200. * StringUtils.isEmpty("") = true
  201. * StringUtils.isEmpty(" ") = false
  202. * StringUtils.isEmpty("bob") = false
  203. * StringUtils.isEmpty(" bob ") = false
  204. * </pre>
  205. *
  206. * <p>NOTE: This method changed in Lang version 2.0.
  207. * It no longer trims the String.
  208. * That functionality is available in isBlank().</p>
  209. *
  210. * @param str the String to check, may be null
  211. * @return <code>true</code> if the String is empty or null
  212. */
  213. public static boolean isEmpty(String str) {
  214. return (str == null || str.length() == 0);
  215. }
  216. /**
  217. * <p>Checks if a String is not empty ("") and not null.</p>
  218. *
  219. * <pre>
  220. * StringUtils.isNotEmpty(null) = false
  221. * StringUtils.isNotEmpty("") = false
  222. * StringUtils.isNotEmpty(" ") = true
  223. * StringUtils.isNotEmpty("bob") = true
  224. * StringUtils.isNotEmpty(" bob ") = true
  225. * </pre>
  226. *
  227. * @param str the String to check, may be null
  228. * @return <code>true</code> if the String is not empty and not null
  229. */
  230. public static boolean isNotEmpty(String str) {
  231. return (str != null && str.length() > 0);
  232. }
  233. /**
  234. * <p>Checks if a String is whitespace, empty ("") or null.</p>
  235. *
  236. * <pre>
  237. * StringUtils.isBlank(null) = true
  238. * StringUtils.isBlank("") = true
  239. * StringUtils.isBlank(" ") = true
  240. * StringUtils.isBlank("bob") = false
  241. * StringUtils.isBlank(" bob ") = false
  242. * </pre>
  243. *
  244. * @param str the String to check, may be null
  245. * @return <code>true</code> if the String is null, empty or whitespace
  246. * @since 2.0
  247. */
  248. public static boolean isBlank(String str) {
  249. int strLen;
  250. if (str == null || (strLen = str.length()) == 0) {
  251. return true;
  252. }
  253. for (int i = 0; i < strLen; i++) {
  254. if ((Character.isWhitespace(str.charAt(i)) == false) ) {
  255. return false;
  256. }
  257. }
  258. return true;
  259. }
  260. /**
  261. * <p>Checks if a String is not empty (""), not null and not whitespace only.</p>
  262. *
  263. * <pre>
  264. * StringUtils.isNotBlank(null) = false
  265. * StringUtils.isNotBlank("") = false
  266. * StringUtils.isNotBlank(" ") = false
  267. * StringUtils.isNotBlank("bob") = true
  268. * StringUtils.isNotBlank(" bob ") = true
  269. * </pre>
  270. *
  271. * @param str the String to check, may be null
  272. * @return <code>true</code> if the String is
  273. * not empty and not null and not whitespace
  274. * @since 2.0
  275. */
  276. public static boolean isNotBlank(String str) {
  277. int strLen;
  278. if (str == null || (strLen = str.length()) == 0) {
  279. return false;
  280. }
  281. for (int i = 0; i < strLen; i++) {
  282. if ((Character.isWhitespace(str.charAt(i)) == false) ) {
  283. return true;
  284. }
  285. }
  286. return false;
  287. }
  288. // Trim
  289. //-----------------------------------------------------------------------
  290. /**
  291. * <p>Removes control characters (char <= 32) from both
  292. * ends of this String, handling <code>null</code> by returning
  293. * an empty String ("").</p>
  294. *
  295. * <pre>
  296. * StringUtils.clean(null) = ""
  297. * StringUtils.clean("") = ""
  298. * StringUtils.clean("abc") = "abc"
  299. * StringUtils.clean(" abc ") = "abc"
  300. * StringUtils.clean(" ") = ""
  301. * </pre>
  302. *
  303. * @see java.lang.String#trim()
  304. * @param str the String to clean, may be null
  305. * @return the trimmed text, never <code>null</code>
  306. * @deprecated Use the clearer named {@link #trimToEmpty(String)}.
  307. * Method will be removed in Commons Lang 3.0.
  308. */
  309. public static String clean(String str) {
  310. return (str == null ? EMPTY : str.trim());
  311. }
  312. /**
  313. * <p>Removes control characters (char <= 32) from both
  314. * ends of this String, handling <code>null</code> by returning
  315. * <code>null</code>.</p>
  316. *
  317. * <p>The String is trimmed using {@link String#trim()}.
  318. * Trim removes start and end characters <= 32.
  319. * To strip whitespace use {@link #strip(String)}.</p>
  320. *
  321. * <p>To trim your choice of characters, use the
  322. * {@link #strip(String, String)} methods.</p>
  323. *
  324. * <pre>
  325. * StringUtils.trim(null) = null
  326. * StringUtils.trim("") = ""
  327. * StringUtils.trim(" ") = ""
  328. * StringUtils.trim("abc") = "abc"
  329. * StringUtils.trim(" abc ") = "abc"
  330. * </pre>
  331. *
  332. * @param str the String to be trimmed, may be null
  333. * @return the trimmed string, <code>null</code> if null String input
  334. */
  335. public static String trim(String str) {
  336. return (str == null ? null : str.trim());
  337. }
  338. /**
  339. * <p>Removes control characters (char <= 32) from both
  340. * ends of this String returning <code>null</code> if the String is
  341. * empty ("") after the trim or if it is <code>null</code>.
  342. *
  343. * <p>The String is trimmed using {@link String#trim()}.
  344. * Trim removes start and end characters <= 32.
  345. * To strip whitespace use {@link #stripToNull(String)}.</p>
  346. *
  347. * <pre>
  348. * StringUtils.trimToNull(null) = null
  349. * StringUtils.trimToNull("") = null
  350. * StringUtils.trimToNull(" ") = null
  351. * StringUtils.trimToNull("abc") = "abc"
  352. * StringUtils.trimToNull(" abc ") = "abc"
  353. * </pre>
  354. *
  355. * @param str the String to be trimmed, may be null
  356. * @return the trimmed String,
  357. * <code>null</code> if only chars <= 32, empty or null String input
  358. * @since 2.0
  359. */
  360. public static String trimToNull(String str) {
  361. String ts = trim(str);
  362. return (ts == null || ts.length() == 0 ? null : ts);
  363. }
  364. /**
  365. * <p>Removes control characters (char <= 32) from both
  366. * ends of this String returning an empty String ("") if the String
  367. * is empty ("") after the trim or if it is <code>null</code>.
  368. *
  369. * <p>The String is trimmed using {@link String#trim()}.
  370. * Trim removes start and end characters <= 32.
  371. * To strip whitespace use {@link #stripToEmpty(String)}.</p>
  372. *
  373. * <pre>
  374. * StringUtils.trimToEmpty(null) = ""
  375. * StringUtils.trimToEmpty("") = ""
  376. * StringUtils.trimToEmpty(" ") = ""
  377. * StringUtils.trimToEmpty("abc") = "abc"
  378. * StringUtils.trimToEmpty(" abc ") = "abc"
  379. * </pre>
  380. *
  381. * @param str the String to be trimmed, may be null
  382. * @return the trimmed String, or an empty String if <code>null</code> input
  383. * @since 2.0
  384. */
  385. public static String trimToEmpty(String str) {
  386. return (str == null ? EMPTY : str.trim());
  387. }
  388. // Stripping
  389. //-----------------------------------------------------------------------
  390. /**
  391. * <p>Strips whitespace from the start and end of a String.</p>
  392. *
  393. * <p>This is similar to {@link #trim(String)} but removes whitespace.
  394. * Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
  395. *
  396. * <p>A <code>null</code> input String returns <code>null</code>.</p>
  397. *
  398. * <pre>
  399. * StringUtils.strip(null) = null
  400. * StringUtils.strip("") = ""
  401. * StringUtils.strip(" ") = ""
  402. * StringUtils.strip("abc") = "abc"
  403. * StringUtils.strip(" abc") = "abc"
  404. * StringUtils.strip("abc ") = "abc"
  405. * StringUtils.strip(" abc ") = "abc"
  406. * StringUtils.strip(" ab c ") = "ab c"
  407. * </pre>
  408. *
  409. * @param str the String to remove whitespace from, may be null
  410. * @return the stripped String, <code>null</code> if null String input
  411. */
  412. public static String strip(String str) {
  413. return strip(str, null);
  414. }
  415. /**
  416. * <p>Strips whitespace from the start and end of a String returning
  417. * <code>null</code> if the String is empty ("") after the strip.</p>
  418. *
  419. * <p>This is similar to {@link #trimToNull(String)} but removes whitespace.
  420. * Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
  421. *
  422. * <pre>
  423. * StringUtils.strip(null) = null
  424. * StringUtils.strip("") = null
  425. * StringUtils.strip(" ") = null
  426. * StringUtils.strip("abc") = "abc"
  427. * StringUtils.strip(" abc") = "abc"
  428. * StringUtils.strip("abc ") = "abc"
  429. * StringUtils.strip(" abc ") = "abc"
  430. * StringUtils.strip(" ab c ") = "ab c"
  431. * </pre>
  432. *
  433. * @param str the String to be stripped, may be null
  434. * @return the stripped String,
  435. * <code>null</code> if whitespace, empty or null String input
  436. * @since 2.0
  437. */
  438. public static String stripToNull(String str) {
  439. if (str == null) {
  440. return null;
  441. }
  442. str = strip(str, null);
  443. return (str.length() == 0 ? null : str);
  444. }
  445. /**
  446. * <p>Strips whitespace from the start and end of a String returning
  447. * an empty String if <code>null</code> input.</p>
  448. *
  449. * <p>This is similar to {@link #trimToEmpty(String)} but removes whitespace.
  450. * Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
  451. *
  452. * <pre>
  453. * StringUtils.strip(null) = ""
  454. * StringUtils.strip("") = ""
  455. * StringUtils.strip(" ") = ""
  456. * StringUtils.strip("abc") = "abc"
  457. * StringUtils.strip(" abc") = "abc"
  458. * StringUtils.strip("abc ") = "abc"
  459. * StringUtils.strip(" abc ") = "abc"
  460. * StringUtils.strip(" ab c ") = "ab c"
  461. * </pre>
  462. *
  463. * @param str the String to be stripped, may be null
  464. * @return the trimmed String, or an empty String if <code>null</code> input
  465. * @since 2.0
  466. */
  467. public static String stripToEmpty(String str) {
  468. return (str == null ? EMPTY : strip(str, null));
  469. }
  470. /**
  471. * <p>Strips any of a set of characters from the start and end of a String.
  472. * This is similar to {@link String#trim()} but allows the characters
  473. * to be stripped to be controlled.</p>
  474. *
  475. * <p>A <code>null</code> input String returns <code>null</code>.
  476. * An empty string ("") input returns the empty string.</p>
  477. *
  478. * <p>If the stripChars String is <code>null</code>, whitespace is
  479. * stripped as defined by {@link Character#isWhitespace(char)}.
  480. * Alternatively use {@link #strip(String)}.</p>
  481. *
  482. * <pre>
  483. * StringUtils.strip(null, *) = null
  484. * StringUtils.strip("", *) = ""
  485. * StringUtils.strip("abc", null) = "abc"
  486. * StringUtils.strip(" abc", null) = "abc"
  487. * StringUtils.strip("abc ", null) = "abc"
  488. * StringUtils.strip(" abc ", null) = "abc"
  489. * StringUtils.strip(" abcyx", "xyz") = " abc"
  490. * </pre>
  491. *
  492. * @param str the String to remove characters from, may be null
  493. * @param stripChars the characters to remove, null treated as whitespace
  494. * @return the stripped String, <code>null</code> if null String input
  495. */
  496. public static String strip(String str, String stripChars) {
  497. if (str == null || str.length() == 0) {
  498. return str;
  499. }
  500. str = stripStart(str, stripChars);
  501. return stripEnd(str, stripChars);
  502. }
  503. /**
  504. * <p>Strips any of a set of characters from the start of a String.</p>
  505. *
  506. * <p>A <code>null</code> input String returns <code>null</code>.
  507. * An empty string ("") input returns the empty string.</p>
  508. *
  509. * <p>If the stripChars String is <code>null</code>, whitespace is
  510. * stripped as defined by {@link Character#isWhitespace(char)}.</p>
  511. *
  512. * <pre>
  513. * StringUtils.stripStart(null, *) = null
  514. * StringUtils.stripStart("", *) = ""
  515. * StringUtils.stripStart("abc", "") = "abc"
  516. * StringUtils.stripStart("abc", null) = "abc"
  517. * StringUtils.stripStart(" abc", null) = "abc"
  518. * StringUtils.stripStart("abc ", null) = "abc "
  519. * StringUtils.stripStart(" abc ", null) = "abc "
  520. * StringUtils.stripStart("yxabc ", "xyz") = "abc "
  521. * </pre>
  522. *
  523. * @param str the String to remove characters from, may be null
  524. * @param stripChars the characters to remove, null treated as whitespace
  525. * @return the stripped String, <code>null</code> if null String input
  526. */
  527. public static String stripStart(String str, String stripChars) {
  528. int strLen;
  529. if (str == null || (strLen = str.length()) == 0) {
  530. return str;
  531. }
  532. int start = 0;
  533. if (stripChars == null) {
  534. while ((start != strLen) && Character.isWhitespace(str.charAt(start))) {
  535. start++;
  536. }
  537. } else if (stripChars.length() == 0) {
  538. return str;
  539. } else {
  540. while ((start != strLen) && (stripChars.indexOf(str.charAt(start)) != -1)) {
  541. start++;
  542. }
  543. }
  544. return str.substring(start);
  545. }
  546. /**
  547. * <p>Strips any of a set of characters from the end of a String.</p>
  548. *
  549. * <p>A <code>null</code> input String returns <code>null</code>.
  550. * An empty string ("") input returns the empty string.</p>
  551. *
  552. * <p>If the stripChars String is <code>null</code>, whitespace is
  553. * stripped as defined by {@link Character#isWhitespace(char)}.</p>
  554. *
  555. * <pre>
  556. * StringUtils.stripEnd(null, *) = null
  557. * StringUtils.stripEnd("", *) = ""
  558. * StringUtils.stripEnd("abc", "") = "abc"
  559. * StringUtils.stripEnd("abc", null) = "abc"
  560. * StringUtils.stripEnd(" abc", null) = " abc"
  561. * StringUtils.stripEnd("abc ", null) = "abc"
  562. * StringUtils.stripEnd(" abc ", null) = " abc"
  563. * StringUtils.stripEnd(" abcyx", "xyz") = " abc"
  564. * </pre>
  565. *
  566. * @param str the String to remove characters from, may be null
  567. * @param stripChars the characters to remove, null treated as whitespace
  568. * @return the stripped String, <code>null</code> if null String input
  569. */
  570. public static String stripEnd(String str, String stripChars) {
  571. int end;
  572. if (str == null || (end = str.length()) == 0) {
  573. return str;
  574. }
  575. if (stripChars == null) {
  576. while ((end != 0) && Character.isWhitespace(str.charAt(end - 1))) {
  577. end--;
  578. }
  579. } else if (stripChars.length() == 0) {
  580. return str;
  581. } else {
  582. while ((end != 0) && (stripChars.indexOf(str.charAt(end - 1)) != -1)) {
  583. end--;
  584. }
  585. }
  586. return str.substring(0, end);
  587. }
  588. // StripAll
  589. //-----------------------------------------------------------------------
  590. /**
  591. * <p>Strips whitespace from the start and end of every String in an array.
  592. * Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
  593. *
  594. * <p>A new array is returned each time, except for length zero.
  595. * A <code>null</code> array will return <code>null</code>.
  596. * An empty array will return itself.
  597. * A <code>null</code> array entry will be ignored.</p>
  598. *
  599. * <pre>
  600. * StringUtils.stripAll(null) = null
  601. * StringUtils.stripAll([]) = []
  602. * StringUtils.stripAll(["abc", " abc"]) = ["abc", "abc"]
  603. * StringUtils.stripAll(["abc ", null]) = ["abc", null]
  604. * </pre>
  605. *
  606. * @param strs the array to remove whitespace from, may be null
  607. * @return the stripped Strings, <code>null</code> if null array input
  608. */
  609. public static String[] stripAll(String[] strs) {
  610. return stripAll(strs, null);
  611. }
  612. /**
  613. * <p>Strips any of a set of characters from the start and end of every
  614. * String in an array.</p>
  615. * Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
  616. *
  617. * <p>A new array is returned each time, except for length zero.
  618. * A <code>null</code> array will return <code>null</code>.
  619. * An empty array will return itself.
  620. * A <code>null</code> array entry will be ignored.
  621. * A <code>null</code> stripChars will strip whitespace as defined by
  622. * {@link Character#isWhitespace(char)}.</p>
  623. *
  624. * <pre>
  625. * StringUtils.stripAll(null, *) = null
  626. * StringUtils.stripAll([], *) = []
  627. * StringUtils.stripAll(["abc", " abc"], null) = ["abc", "abc"]
  628. * StringUtils.stripAll(["abc ", null], null) = ["abc", null]
  629. * StringUtils.stripAll(["abc ", null], "yz") = ["abc ", null]
  630. * StringUtils.stripAll(["yabcz", null], "yz") = ["abc", null]
  631. * </pre>
  632. *
  633. * @param strs the array to remove characters from, may be null
  634. * @param stripChars the characters to remove, null treated as whitespace
  635. * @return the stripped Strings, <code>null</code> if null array input
  636. */
  637. public static String[] stripAll(String[] strs, String stripChars) {
  638. int strsLen;
  639. if (strs == null || (strsLen = strs.length) == 0) {
  640. return strs;
  641. }
  642. String[] newArr = new String[strsLen];
  643. for (int i = 0; i < strsLen; i++) {
  644. newArr[i] = strip(strs[i], stripChars);
  645. }
  646. return newArr;
  647. }
  648. // Equals
  649. //-----------------------------------------------------------------------
  650. /**
  651. * <p>Compares two Strings, returning <code>true</code> if they are equal.</p>
  652. *
  653. * <p><code>null</code>s are handled without exceptions. Two <code>null</code>
  654. * references are considered to be equal. The comparison is case sensitive.</p>
  655. *
  656. * <pre>
  657. * StringUtils.equals(null, null) = true
  658. * StringUtils.equals(null, "abc") = false
  659. * StringUtils.equals("abc", null) = false
  660. * StringUtils.equals("abc", "abc") = true
  661. * StringUtils.equals("abc", "ABC") = false
  662. * </pre>
  663. *
  664. * @see java.lang.String#equals(Object)
  665. * @param str1 the first String, may be null
  666. * @param str2 the second String, may be null
  667. * @return <code>true</code> if the Strings are equal, case sensitive, or
  668. * both <code>null</code>
  669. */
  670. public static boolean equals(String str1, String str2) {
  671. return (str1 == null ? str2 == null : str1.equals(str2));
  672. }
  673. /**
  674. * <p>Compares two Strings, returning <code>true</code> if they are equal ignoring
  675. * the case.</p>
  676. *
  677. * <p><code>null</code>s are handled without exceptions. Two <code>null</code>
  678. * references are considered equal. Comparison is case insensitive.</p>
  679. *
  680. * <pre>
  681. * StringUtils.equalsIgnoreCase(null, null) = true
  682. * StringUtils.equalsIgnoreCase(null, "abc") = false
  683. * StringUtils.equalsIgnoreCase("abc", null) = false
  684. * StringUtils.equalsIgnoreCase("abc", "abc") = true
  685. * StringUtils.equalsIgnoreCase("abc", "ABC") = true
  686. * </pre>
  687. *
  688. * @see java.lang.String#equalsIgnoreCase(String)
  689. * @param str1 the first String, may be null
  690. * @param str2 the second String, may be null
  691. * @return <code>true</code> if the Strings are equal, case insensitive, or
  692. * both <code>null</code>
  693. */
  694. public static boolean equalsIgnoreCase(String str1, String str2) {
  695. return (str1 == null ? str2 == null : str1.equalsIgnoreCase(str2));
  696. }
  697. // IndexOf
  698. //-----------------------------------------------------------------------
  699. /**
  700. * <p>Finds the first index within a String, handling <code>null</code>.
  701. * This method uses {@link String#indexOf(int)}.</p>
  702. *
  703. * <p>A <code>null</code> or empty ("") String will return <code>-1</code>.</p>
  704. *
  705. * <pre>
  706. * StringUtils.indexOf(null, *) = -1
  707. * StringUtils.indexOf("", *) = -1
  708. * StringUtils.indexOf("aabaabaa", 'a') = 0
  709. * StringUtils.indexOf("aabaabaa", 'b') = 2
  710. * </pre>
  711. *
  712. * @param str the String to check, may be null
  713. * @param searchChar the character to find
  714. * @return the first index of the search character,
  715. * -1 if no match or <code>null</code> string input
  716. * @since 2.0
  717. */
  718. public static int indexOf(String str, char searchChar) {
  719. if (str == null || str.length() == 0) {
  720. return -1;
  721. }
  722. return str.indexOf(searchChar);
  723. }
  724. /**
  725. * <p>Finds the first index within a String from a start position,
  726. * handling <code>null</code>.
  727. * This method uses {@link String#indexOf(int, int)}.</p>
  728. *
  729. * <p>A <code>null</code> or empty ("") String will return <code>-1</code>.
  730. * A negative start position is treated as zero.
  731. * A start position greater than the string length returns <code>-1</code>.</p>
  732. *
  733. * <pre>
  734. * StringUtils.indexOf(null, *, *) = -1
  735. * StringUtils.indexOf("", *, *) = -1
  736. * StringUtils.indexOf("aabaabaa", 'b', 0) = 2
  737. * StringUtils.indexOf("aabaabaa", 'b', 3) = 5
  738. * StringUtils.indexOf("aabaabaa", 'b', 9) = -1
  739. * StringUtils.indexOf("aabaabaa", 'b', -1) = 2
  740. * </pre>
  741. *
  742. * @param str the String to check, may be null
  743. * @param searchChar the character to find
  744. * @param startPos the start position, negative treated as zero
  745. * @return the first index of the search character,
  746. * -1 if no match or <code>null</code> string input
  747. * @since 2.0
  748. */
  749. public static int indexOf(String str, char searchChar, int startPos) {
  750. if (str == null || str.length() == 0) {
  751. return -1;
  752. }
  753. return str.indexOf(searchChar, startPos);
  754. }
  755. /**
  756. * <p>Finds the first index within a String, handling <code>null</code>.
  757. * This method uses {@link String#indexOf(String)}.</p>
  758. *
  759. * <p>A <code>null</code> String will return <code>-1</code>.</p>
  760. *
  761. * <pre>
  762. * StringUtils.indexOf(null, *) = -1
  763. * StringUtils.indexOf(*, null) = -1
  764. * StringUtils.indexOf("", "") = 0
  765. * StringUtils.indexOf("aabaabaa", "a") = 0
  766. * StringUtils.indexOf("aabaabaa", "b") = 2
  767. * StringUtils.indexOf("aabaabaa", "ab") = 1
  768. * StringUtils.indexOf("aabaabaa", "") = 0
  769. * </pre>
  770. *
  771. * @param str the String to check, may be null
  772. * @param searchStr the String to find, may be null
  773. * @return the first index of the search String,
  774. * -1 if no match or <code>null</code> string input
  775. * @since 2.0
  776. */
  777. public static int indexOf(String str, String searchStr) {
  778. if (str == null || searchStr == null) {
  779. return -1;
  780. }
  781. return str.indexOf(searchStr);
  782. }
  783. /**
  784. * <p>Finds the first index within a String, handling <code>null</code>.
  785. * This method uses {@link String#indexOf(String, int)}.</p>
  786. *
  787. * <p>A <code>null</code> String will return <code>-1</code>.
  788. * A negative start position is treated as zero.
  789. * An empty ("") search String always matches.
  790. * A start position greater than the string length only matches
  791. * an empty search String.</p>
  792. *
  793. * <pre>
  794. * StringUtils.indexOf(null, *, *) = -1
  795. * StringUtils.indexOf(*, null, *) = -1
  796. * StringUtils.indexOf("", "", 0) = 0
  797. * StringUtils.indexOf("aabaabaa", "a", 0) = 0
  798. * StringUtils.indexOf("aabaabaa", "b", 0) = 2
  799. * StringUtils.indexOf("aabaabaa", "ab", 0) = 1
  800. * StringUtils.indexOf("aabaabaa", "b", 3) = 5
  801. * StringUtils.indexOf("aabaabaa", "b", 9) = -1
  802. * StringUtils.indexOf("aabaabaa", "b", -1) = 2
  803. * StringUtils.indexOf("aabaabaa", "", 2) = 2
  804. * StringUtils.indexOf("abc", "", 9) = 3
  805. * </pre>
  806. *
  807. * @param str the String to check, may be null
  808. * @param searchStr the String to find, may be null
  809. * @param startPos the start position, negative treated as zero
  810. * @return the first index of the search String,
  811. * -1 if no match or <code>null</code> string input
  812. * @since 2.0
  813. */
  814. public static int indexOf(String str, String searchStr, int startPos) {
  815. if (str == null || searchStr == null) {
  816. return -1;
  817. }
  818. // JDK1.2/JDK1.3 have a bug, when startPos > str.length for "", hence
  819. if (searchStr.length() == 0 && startPos >= str.length()) {
  820. return str.length();
  821. }
  822. return str.indexOf(searchStr, startPos);
  823. }
  824. // LastIndexOf
  825. //-----------------------------------------------------------------------
  826. /**
  827. * <p>Finds the last index within a String, handling <code>null</code>.
  828. * This method uses {@link String#lastIndexOf(int)}.</p>
  829. *
  830. * <p>A <code>null</code> or empty ("") String will return <code>-1</code>.</p>
  831. *
  832. * <pre>
  833. * StringUtils.lastIndexOf(null, *) = -1
  834. * StringUtils.lastIndexOf("", *) = -1
  835. * StringUtils.lastIndexOf("aabaabaa", 'a') = 7
  836. * StringUtils.lastIndexOf("aabaabaa", 'b') = 5
  837. * </pre>
  838. *
  839. * @param str the String to check, may be null
  840. * @param searchChar the character to find
  841. * @return the last index of the search character,
  842. * -1 if no match or <code>null</code> string input
  843. * @since 2.0
  844. */
  845. public static int lastIndexOf(String str, char searchChar) {
  846. if (str == null || str.length() == 0) {
  847. return -1;
  848. }
  849. return str.lastIndexOf(searchChar);
  850. }
  851. /**
  852. * <p>Finds the last index within a String from a start position,
  853. * handling <code>null</code>.
  854. * This method uses {@link String#lastIndexOf(int, int)}.</p>
  855. *
  856. * <p>A <code>null</code> or empty ("") String will return <code>-1</code>.
  857. * A negative start position returns <code>-1</code>.
  858. * A start position greater than the string length searches the whole string.</p>
  859. *
  860. * <pre>
  861. * StringUtils.lastIndexOf(null, *, *) = -1
  862. * StringUtils.lastIndexOf("", *, *) = -1
  863. * StringUtils.lastIndexOf("aabaabaa", 'b', 8) = 5
  864. * StringUtils.lastIndexOf("aabaabaa", 'b', 4) = 2
  865. * StringUtils.lastIndexOf("aabaabaa", 'b', 0) = -1
  866. * StringUtils.lastIndexOf("aabaabaa", 'b', 9) = 5
  867. * StringUtils.lastIndexOf("aabaabaa", 'b', -1) = -1
  868. * StringUtils.lastIndexOf("aabaabaa", 'a', 0) = 0
  869. * </pre>
  870. *
  871. * @param str the String to check, may be null
  872. * @param searchChar the character to find
  873. * @param startPos the start position
  874. * @return the last index of the search character,
  875. * -1 if no match or <code>null</code> string input
  876. * @since 2.0
  877. */
  878. public static int lastIndexOf(String str, char searchChar, int startPos) {
  879. if (str == null || str.length() == 0) {
  880. return -1;
  881. }
  882. return str.lastIndexOf(searchChar, startPos);
  883. }
  884. /**
  885. * <p>Finds the last index within a String, handling <code>null</code>.
  886. * This method uses {@link String#lastIndexOf(String)}.</p>
  887. *
  888. * <p>A <code>null</code> String will return <code>-1</code>.</p>
  889. *
  890. * <pre>
  891. * StringUtils.lastIndexOf(null, *) = -1
  892. * StringUtils.lastIndexOf(*, null) = -1
  893. * StringUtils.lastIndexOf("", "") = 0
  894. * StringUtils.lastIndexOf("aabaabaa", "a") = 0
  895. * StringUtils.lastIndexOf("aabaabaa", "b") = 2
  896. * StringUtils.lastIndexOf("aabaabaa", "ab") = 1
  897. * StringUtils.lastIndexOf("aabaabaa", "") = 8
  898. * </pre>
  899. *
  900. * @param str the String to check, may be null
  901. * @param searchStr the String to find, may be null
  902. * @return the last index of the search String,
  903. * -1 if no match or <code>null</code> string input
  904. * @since 2.0
  905. */
  906. public static int lastIndexOf(String str, String searchStr) {
  907. if (str == null || searchStr == null) {
  908. return -1;
  909. }
  910. return str.lastIndexOf(searchStr);
  911. }
  912. /**
  913. * <p>Finds the first index within a String, handling <code>null</code>.
  914. * This method uses {@link String#lastIndexOf(String, int)}.</p>
  915. *
  916. * <p>A <code>null</code> String will return <code>-1</code>.
  917. * A negative start position returns <code>-1</code>.
  918. * An empty ("") search String always matches unless the start position is negative.
  919. * A start position greater than the string length searches the whole string.</p>
  920. *
  921. * <pre>
  922. * StringUtils.lastIndexOf(null, *, *) = -1
  923. * StringUtils.lastIndexOf(*, null, *) = -1
  924. * StringUtils.lastIndexOf("aabaabaa", "a", 8) = 7
  925. * StringUtils.lastIndexOf("aabaabaa", "b", 8) = 5
  926. * StringUtils.lastIndexOf("aabaabaa", "ab", 8) = 4
  927. * StringUtils.lastIndexOf("aabaabaa", "b", 9) = 5
  928. * StringUtils.lastIndexOf("aabaabaa", "b", -1) = -1
  929. * StringUtils.lastIndexOf("aabaabaa", "a", 0) = 0
  930. * StringUtils.lastIndexOf("aabaabaa", "b", 0) = -1
  931. * </pre>
  932. *
  933. * @param str the String to check, may be null
  934. * @param searchStr the String to find, may be null
  935. * @param startPos the start position, negative treated as zero
  936. * @return the first index of the search String,
  937. * -1 if no match or <code>null</code> string input
  938. * @since 2.0
  939. */
  940. public static int lastIndexOf(String str, String searchStr, int startPos) {
  941. if (str == null || searchStr == null) {
  942. return -1;
  943. }
  944. return str.lastIndexOf(searchStr, startPos);
  945. }
  946. // Contains
  947. //-----------------------------------------------------------------------
  948. /**
  949. * <p>Checks if String contains a search character, handling <code>null</code>.
  950. * This method uses {@link String#indexOf(int)}.</p>
  951. *
  952. * <p>A <code>null</code> or empty ("") String will return <code>false</code>.</p>
  953. *
  954. * <pre>
  955. * StringUtils.contains(null, *) = false
  956. * StringUtils.contains("", *) = false
  957. * StringUtils.contains("abc", 'a') = true
  958. * StringUtils.contains("abc", 'z') = false
  959. * </pre>
  960. *
  961. * @param str the String to check, may be null
  962. * @param searchChar the character to find
  963. * @return true if the String contains the search character,
  964. * false if not or <code>null</code> string input
  965. * @since 2.0
  966. */
  967. public static boolean contains(String str, char searchChar) {
  968. if (str == null || str.length() == 0) {
  969. return false;
  970. }
  971. return (str.indexOf(searchChar) >= 0);
  972. }
  973. /**
  974. * <p>Find the first index within a String, handling <code>null</code>.
  975. * This method uses {@link String#indexOf(int)}.</p>
  976. *
  977. * <p>A <code>null</code> String will return <code>false</code>.</p>
  978. *
  979. * <pre>
  980. * StringUtils.contains(null, *) = false
  981. * StringUtils.contains(*, null) = false
  982. * StringUtils.contains("", "") = true
  983. * StringUtils.contains("abc", "") = true
  984. * StringUtils.contains("abc", "a") = true
  985. * StringUtils.contains("abc", "z") = false
  986. * </pre>
  987. *
  988. * @param str the String to check, may be null
  989. * @param searchStr the String to find, may be null
  990. * @return true if the String contains the search character,
  991. * false if not or <code>null</code> string input
  992. * @since 2.0
  993. */
  994. public static boolean contains(String str, String searchStr) {
  995. if (str == null || searchStr == null) {
  996. return false;
  997. }
  998. return (str.indexOf(searchStr) >= 0);
  999. }
  1000. // IndexOfAny chars
  1001. //-----------------------------------------------------------------------
  1002. /**
  1003. * <p>Search a String to find the first index of any
  1004. * character in the given set of characters.</p>
  1005. *
  1006. * <p>A <code>null</code> String will return <code>-1</code>.
  1007. * A <code>null</code> or zero length search array will return <code>-1</code>.</p>
  1008. *
  1009. * <pre>
  1010. * StringUtils.indexOfAny(null, *) = -1
  1011. * StringUtils.indexOfAny("", *) = -1
  1012. * StringUtils.indexOfAny(*, null) = -1
  1013. * StringUtils.indexOfAny(*, []) = -1
  1014. * StringUtils.indexOfAny("zzabyycdxx",['z','a']) = 0
  1015. * StringUtils.indexOfAny("zzabyycdxx",['b','y']) = 3
  1016. * StringUtils.indexOfAny("aba", ['z']) = -1
  1017. * </pre>
  1018. *
  1019. * @param str the String to check, may be null
  1020. * @param searchChars the chars to search for, may be null
  1021. * @return the index of any of the chars, -1 if no match or null input
  1022. * @since 2.0
  1023. */
  1024. public static int indexOfAny(String str, char[] searchChars) {
  1025. if (str == null || str.length() == 0 || searchChars == null || searchChars.length == 0) {
  1026. return -1;
  1027. }
  1028. for (int i = 0; i < str.length(); i ++) {
  1029. char ch = str.charAt(i);
  1030. for (int j = 0; j < searchChars.length; j++) {
  1031. if (searchChars[j] == ch) {
  1032. return i;
  1033. }
  1034. }
  1035. }
  1036. return -1;
  1037. }
  1038. /**
  1039. * <p>Search a String to find the first index of any
  1040. * character in the given set of characters.</p>
  1041. *
  1042. * <p>A <code>null</code> String will return <code>-1</code>.
  1043. * A <code>null</code> search string will return <code>-1</code>.</p>
  1044. *
  1045. * <pre>
  1046. * StringUtils.indexOfAny(null, *) = -1
  1047. * StringUtils.indexOfAny("", *) = -1
  1048. * StringUtils.indexOfAny(*, null) = -1
  1049. * StringUtils.indexOfAny(*, "") = -1
  1050. * StringUtils.indexOfAny("zzabyycdxx", "za") = 0
  1051. * StringUtils.indexOfAny("zzabyycdxx", "by") = 3
  1052. * StringUtils.indexOfAny("aba","z") = -1
  1053. * </pre>
  1054. *
  1055. * @param str the String to check, may be null
  1056. * @param searchChars the chars to search for, may be null
  1057. * @return the index of any of the chars, -1 if no match or null input
  1058. * @since 2.0
  1059. */
  1060. public static int indexOfAny(String str, String searchChars) {
  1061. if (str == null || str.length() == 0 || searchChars == null || searchChars.length() == 0) {
  1062. return -1;
  1063. }
  1064. return indexOfAny(str, searchChars.toCharArray());
  1065. }
  1066. // IndexOfAnyBut chars
  1067. //-----------------------------------------------------------------------
  1068. /**
  1069. * <p>Search a String to find the first index of any
  1070. * character not in the given set of characters.</p>
  1071. *
  1072. * <p>A <code>null</code> String will return <code>-1</code>.
  1073. * A <code>null</code> or zero length search array will return <code>-1</code>.</p>
  1074. *
  1075. * <pre>
  1076. * StringUtils.indexOfAnyBut(null, *) = -1
  1077. * StringUtils.indexOfAnyBut("", *) = -1
  1078. * StringUtils.indexOfAnyBut(*, null) = -1
  1079. * StringUtils.indexOfAnyBut(*, []) = -1
  1080. * StringUtils.indexOfAnyBut("zzabyycdxx",'za') = 3
  1081. * StringUtils.indexOfAnyBut("zzabyycdxx", '') = 0
  1082. * StringUtils.indexOfAnyBut("aba", 'ab') = -1
  1083. * </pre>
  1084. *
  1085. * @param str the String to check, may be null
  1086. * @param searchChars the chars to search for, may be null
  1087. * @return the index of any of the chars, -1 if no match or null input
  1088. * @since 2.0
  1089. */
  1090. public static int indexOfAnyBut(String str, char[] searchChars) {
  1091. if (str == null || str.length() == 0 || searchChars == null || searchChars.length == 0) {
  1092. return -1;
  1093. }
  1094. outer: for (int i = 0; i < str.length(); i ++) {
  1095. char ch = str.charAt(i);
  1096. for (int j = 0; j < searchChars.length; j++) {
  1097. if (searchChars[j] == ch) {
  1098. continue outer;
  1099. }
  1100. }
  1101. return i;
  1102. }
  1103. return -1;
  1104. }
  1105. /**
  1106. * <p>Search a String to find the first index of any
  1107. * character not in the given set of characters.</p>
  1108. *
  1109. * <p>A <code>null</code> String will return <code>-1</code>.
  1110. * A <code>null</code> search string will return <code>-1</code>.</p>
  1111. *
  1112. * <pre>
  1113. * StringUtils.indexOfAnyBut(null, *) = -1
  1114. * StringUtils.indexOfAnyBut("", *) = -1
  1115. * StringUtils.indexOfAnyBut(*, null) = -1
  1116. * StringUtils.indexOfAnyBut(*, "") = -1
  1117. * StringUtils.indexOfAnyBut("zzabyycdxx", "za") = 3
  1118. * StringUtils.indexOfAnyBut("zzabyycdxx", "") = 0
  1119. * StringUtils.indexOfAnyBut("aba","ab") = -1
  1120. * </pre>
  1121. *
  1122. * @param str the String to check, may be null
  1123. * @param searchChars the chars to search for, may be null
  1124. * @return the index of any of the chars, -1 if no match or null input
  1125. * @since 2.0
  1126. */
  1127. public static int indexOfAnyBut(String str, String searchChars) {
  1128. if (str == null || str.length() == 0 || searchChars == null || searchChars.length() == 0) {
  1129. return -1;
  1130. }
  1131. for (int i = 0; i < str.length(); i++) {
  1132. if (searchChars.indexOf(str.charAt(i)) < 0) {
  1133. return i;
  1134. }
  1135. }
  1136. return -1;
  1137. }
  1138. // ContainsOnly
  1139. //-----------------------------------------------------------------------
  1140. /**
  1141. * <p>Checks if the String contains only certain characters.</p>
  1142. *
  1143. * <p>A <code>null</code> String will return <code>false</code>.
  1144. * A <code>null</code> valid character array will return <code>false</code>.
  1145. * An empty String ("") always returns <code>true</code>.</p>
  1146. *
  1147. * <pre>
  1148. * StringUtils.containsOnly(null, *) = false
  1149. * StringUtils.containsOnly(*, null) = false
  1150. * StringUtils.containsOnly("", *) = true
  1151. * StringUtils.containsOnly("ab", '') = false
  1152. * StringUtils.containsOnly("abab", 'abc') = true
  1153. * StringUtils.containsOnly("ab1", 'abc') = false
  1154. * StringUtils.containsOnly("abz", 'abc') = false
  1155. * </pre>
  1156. *
  1157. * @param str the String to check, may be null
  1158. * @param valid an array of valid chars, may be null
  1159. * @return true if it only contains valid chars and is non-null
  1160. */
  1161. public static boolean containsOnly(String str, char[] valid) {
  1162. // All these pre-checks are to maintain API with an older version
  1163. if ( (valid == null) || (str == null) ) {
  1164. return false;
  1165. }
  1166. if (str.length() == 0) {
  1167. return true;
  1168. }
  1169. if (valid.length == 0) {
  1170. return false;
  1171. }
  1172. return indexOfAnyBut(str, valid) == -1;
  1173. }
  1174. /**
  1175. * <p>Checks if the String contains only certain characters.</p>
  1176. *
  1177. * <p>A <code>null</code> String will return <code>false</code>.
  1178. * A <code>null</code> valid character String will return <code>false</code>.
  1179. * An empty String ("") always returns <code>true</code>.</p>
  1180. *
  1181. * <pre>
  1182. * StringUtils.containsOnly(null, *) = false
  1183. * StringUtils.containsOnly(*, null) = false
  1184. * StringUtils.containsOnly("", *) = true
  1185. * StringUtils.containsOnly("ab", "") = false
  1186. * StringUtils.containsOnly("abab", "abc") = true
  1187. * StringUtils.containsOnly("ab1", "abc") = false
  1188. * StringUtils.containsOnly("abz", "abc") = false
  1189. * </pre>
  1190. *
  1191. * @param str the String to check, may be null
  1192. * @param validChars a String of valid chars, may be null
  1193. * @return true if it only contains valid chars and is non-null
  1194. * @since 2.0
  1195. */
  1196. public static boolean containsOnly(String str, String validChars) {
  1197. if (str == null || validChars == null) {
  1198. return false;
  1199. }
  1200. return containsOnly(str, validChars.toCharArray());
  1201. }
  1202. // ContainsNone
  1203. //-----------------------------------------------------------------------
  1204. /**
  1205. * <p>Checks that the String does not contain certain characters.</p>
  1206. *
  1207. * <p>A <code>null</code> String will return <code>true</code>.
  1208. * A <code>null</code> invalid character array will return <code>true</code>.
  1209. * An empty String ("") always returns true.</p>
  1210. *
  1211. * <pre>
  1212. * StringUtils.containsNone(null, *) = true
  1213. * StringUtils.containsNone(*, null) = true
  1214. * StringUtils.containsNone("", *) = true
  1215. * StringUtils.containsNone("ab", '') = true
  1216. * StringUtils.containsNone("abab", 'xyz') = true
  1217. * StringUtils.containsNone("ab1", 'xyz') = true
  1218. * StringUtils.containsNone("abz", 'xyz') = false
  1219. * </pre>
  1220. *
  1221. * @param str the String to check, may be null
  1222. * @param invalidChars an array of invalid chars, may be null
  1223. * @return true if it contains none of the invalid chars, or is null
  1224. * @since 2.0
  1225. */
  1226. public static boolean containsNone(String str, char[] invalidChars) {
  1227. if (str == null || invalidChars == null) {
  1228. return true;
  1229. }
  1230. int strSize = str.length();
  1231. int validSize = invalidChars.length;
  1232. for (int i = 0; i < strSize; i++) {
  1233. char ch = str.charAt(i);
  1234. for (int j = 0; j < validSize; j++) {
  1235. if (invalidChars[j] == ch) {
  1236. return false;
  1237. }
  1238. }
  1239. }
  1240. return true;
  1241. }
  1242. /**
  1243. * <p>Checks that the String does not contain certain characters.</p>
  1244. *
  1245. * <p>A <code>null</code> String will return <code>true</code>.
  1246. * A <code>null</code> invalid character array will return <code>true</code>.
  1247. * An empty String ("") always returns true.</p>
  1248. *
  1249. * <pre>
  1250. * StringUtils.containsNone(null, *) = true
  1251. * StringUtils.containsNone(*, null) = true
  1252. * StringUtils.containsNone("", *) = true
  1253. * StringUtils.containsNone("ab", "") = true
  1254. * StringUtils.containsNone("abab", "xyz") = true
  1255. * StringUtils.containsNone("ab1", "xyz") = true
  1256. * StringUtils.containsNone("abz", "xyz") = false
  1257. * </pre>
  1258. *
  1259. * @param str the String to check, may be null
  1260. * @param invalidChars a String of invalid chars, may be null
  1261. * @return true if it contains none of the invalid chars, or is null
  1262. * @since 2.0
  1263. */
  1264. public static boolean containsNone(String str, String invalidChars) {
  1265. if (str == null || invalidChars == null) {
  1266. return true;
  1267. }
  1268. return containsNone(str, invalidChars.toCharArray());
  1269. }
  1270. // IndexOfAny strings
  1271. //-----------------------------------------------------------------------
  1272. /**
  1273. * <p>Find the first index of any of a set of potential substrings.</p>
  1274. *
  1275. * <p>A <code>null</code> String will return <code>-1</code>.
  1276. * A <code>null</code> or zero length search array will return <code>-1</code>.
  1277. * A <code>null</code> search array entry will be ignored, but a search
  1278. * array containing "" will return <code>0</code> if <code>str</code> is not
  1279. * null. This method uses {@link String#indexOf(String)}.</p>
  1280. *
  1281. * <pre>
  1282. * StringUtils.indexOfAny(null, *) = -1
  1283. * StringUtils.indexOfAny(*, null) = -1
  1284. * StringUtils.indexOfAny(*, []) = -1
  1285. * StringUtils.indexOfAny("zzabyycdxx", ["ab","cd"]) = 2
  1286. * StringUtils.indexOfAny("zzabyycdxx", ["cd","ab"]) = 2
  1287. * StringUtils.indexOfAny("zzabyycdxx", ["mn","op"]) = -1
  1288. * StringUtils.indexOfAny("zzabyycdxx", ["zab","aby"]) = 1
  1289. * StringUtils.indexOfAny("zzabyycdxx", [""]) = 0
  1290. * StringUtils.indexOfAny("", [""]) = 0
  1291. * StringUtils.indexOfAny("", ["a"]) = -1
  1292. * </pre>
  1293. *
  1294. * @param str the String to check, may be null
  1295. * @param searchStrs the Strings to search for, may be null
  1296. * @return the first index of any of the searchStrs in str, -1 if no match
  1297. */
  1298. public static int indexOfAny(String str, String[] searchStrs) {
  1299. if ((str == null) || (searchStrs == null)) {
  1300. return -1;
  1301. }
  1302. int sz = searchStrs.length;
  1303. // String's can't have a MAX_VALUEth index.
  1304. int ret = Integer.MAX_VALUE;
  1305. int tmp = 0;
  1306. for (int i = 0; i < sz; i++) {
  1307. String search = searchStrs[i];
  1308. if (search == null) {
  1309. continue;
  1310. }
  1311. tmp = str.indexOf(search);
  1312. if (tmp == -1) {
  1313. continue;
  1314. }
  1315. if (tmp < ret) {
  1316. ret = tmp;
  1317. }
  1318. }
  1319. return (ret == Integer.MAX_VALUE) ? -1 : ret;
  1320. }
  1321. /**
  1322. * <p>Find the latest index of any of a set of potential substrings.</p>
  1323. *
  1324. * <p>A <code>null</code> String will return <code>-1</code>.
  1325. * A <code>null</code> search array will return <code>-1</code>.
  1326. * A <code>null</code> or zero length search array entry will be ignored,
  1327. * but a search array containing "" will return the length of <code>str</code>
  1328. * if <code>str</code> is not null. This method uses {@link String#indexOf(String)}</p>
  1329. *
  1330. * <pre>
  1331. * StringUtils.lastIndexOfAny(null, *) = -1
  1332. * StringUtils.lastIndexOfAny(*, null) = -1
  1333. * StringUtils.lastIndexOfAny(*, []) = -1
  1334. * StringUtils.lastIndexOfAny(*, [null]) = -1
  1335. * StringUtils.lastIndexOfAny("zzabyycdxx", ["ab","cd"]) = 6
  1336. * StringUtils.lastIndexOfAny("zzabyycdxx", ["cd","ab"]) = 6
  1337. * StringUtils.lastIndexOfAny("zzabyycdxx", ["mn","op"]) = -1
  1338. * StringUtils.lastIndexOfAny("zzabyycdxx", ["mn","op"]) = -1
  1339. * StringUtils.lastIndexOfAny("zzabyycdxx", ["mn",""]) = 10
  1340. * </pre>
  1341. *
  1342. * @param str the String to check, may be null
  1343. * @param searchStrs the Strings to search for, may be null
  1344. * @return the last index of any of the Strings, -1 if no match
  1345. */
  1346. public static int lastIndexOfAny(String str, String[] searchStrs) {
  1347. if ((str == null) || (searchStrs == null)) {
  1348. return -1;
  1349. }
  1350. int sz = searchStrs.length;
  1351. int ret = -1;
  1352. int tmp = 0;
  1353. for (int i = 0; i < sz; i++) {
  1354. String search = searchStrs[i];
  1355. if (search == null) {
  1356. continue;
  1357. }
  1358. tmp = str.lastIndexOf(search);
  1359. if (tmp > ret) {
  1360. ret = tmp;
  1361. }
  1362. }
  1363. return ret;
  1364. }
  1365. // Substring
  1366. //-----------------------------------------------------------------------
  1367. /**
  1368. * <p>Gets a substring from the specified String avoiding exceptions.</p>
  1369. *
  1370. * <p>A negative start position can be used to start <code>n</code>
  1371. * characters from the end of the String.</p>
  1372. *
  1373. * <p>A <code>null</code> String will return <code>null</code>.
  1374. * An empty ("") String will return "".</p>
  1375. *
  1376. * <pre>
  1377. * StringUtils.substring(null, *) = null
  1378. * StringUtils.substring("", *) = ""
  1379. * StringUtils.substring("abc", 0) = "abc"
  1380. * StringUtils.substring("abc", 2) = "c"
  1381. * StringUtils.substring("abc", 4) = ""
  1382. * StringUtils.substring("abc", -2) = "bc"
  1383. * StringUtils.substring("abc", -4) = "abc"
  1384. * </pre>
  1385. *
  1386. * @param str the String to get the substring from, may be null
  1387. * @param start the position to start from, negative means
  1388. * count back from the end of the String by this many characters
  1389. * @return substring from start position, <code>null</code> if null String input
  1390. */
  1391. public static String substring(String str, int start) {
  1392. if (str == null) {
  1393. return null;
  1394. }
  1395. // handle negatives, which means last n characters
  1396. if (start < 0) {
  1397. start = str.length() + start; // remember start is negative
  1398. }
  1399. if (start < 0) {
  1400. start = 0;
  1401. }
  1402. if (start > str.length()) {
  1403. return EMPTY;
  1404. }
  1405. return str.substring(start);
  1406. }
  1407. /**
  1408. * <p>Gets a substring from the specified String avoiding exceptions.</p>
  1409. *
  1410. * <p>A negative start position can be used to start/end <code>n</code>
  1411. * characters from the end of the String.</p>
  1412. *
  1413. * <p>The returned substring starts with the character in the <code>start</code>
  1414. * position and ends before the <code>end</code> position. All postion counting is
  1415. * zero-based -- i.e., to start at the beginning of the string use
  1416. * <code>start = 0</code>. Negative start and end positions can be used to
  1417. * specify offsets relative to the end of the String.</p>
  1418. *
  1419. * <p>If <code>start</code> is not strictly to the left of <code>end</code>, ""
  1420. * is returned.</p>
  1421. *
  1422. * <pre>
  1423. * StringUtils.substring(null, *, *) = null
  1424. * StringUtils.substring("", * , *) = "";
  1425. * StringUtils.substring("abc", 0, 2) = "ab"
  1426. * StringUtils.substring("abc", 2, 0) = ""
  1427. * StringUtils.substring("abc", 2, 4) = "c"
  1428. * StringUtils.substring("abc", 4, 6) = ""
  1429. * StringUtils.substring("abc", 2, 2) = ""
  1430. * StringUtils.substring("abc", -2, -1) = "b"
  1431. * StringUtils.substring("abc", -4, 2) = "ab"
  1432. * </pre>
  1433. *
  1434. * @param str the String to get the substring from, may be null
  1435. * @param start the position to start from, negative means
  1436. * count back from the end of the String by this many characters
  1437. * @param end the position to end at (exclusive), negative means
  1438. * count back from the end of the String by this many characters
  1439. * @return substring from start position to end positon,
  1440. * <code>null</code> if null String input
  1441. */
  1442. public static String substring(String str, int start, int end) {
  1443. if (str == null) {
  1444. return null;
  1445. }
  1446. // handle negatives
  1447. if (end < 0) {
  1448. end = str.length() + end; // remember end is negative
  1449. }
  1450. if (start < 0) {
  1451. start = str.length() + start; // remember start is negative
  1452. }
  1453. // check length next
  1454. if (end > str.length()) {
  1455. end = str.length();
  1456. }
  1457. // if start is greater than end, return ""
  1458. if (start > end) {
  1459. return EMPTY;
  1460. }
  1461. if (start < 0) {
  1462. start = 0;
  1463. }
  1464. if (end < 0) {
  1465. end = 0;
  1466. }
  1467. return str.substring(start, end);
  1468. }
  1469. // Left/Right/Mid
  1470. //-----------------------------------------------------------------------
  1471. /**
  1472. * <p>Gets the leftmost <code>len</code> characters of a String.</p>
  1473. *
  1474. * <p>If <code>len</code> characters are not available, or the
  1475. * String is <code>null</code>, the String will be returned without
  1476. * an exception. An exception is thrown if len is negative.</p>
  1477. *
  1478. * <pre>
  1479. * StringUtils.left(null, *) = null
  1480. * StringUtils.left(*, -ve) = ""
  1481. * StringUtils.left("", *) = ""
  1482. * StringUtils.left("abc", 0) = ""
  1483. * StringUtils.left("abc", 2) = "ab"
  1484. * StringUtils.left("abc", 4) = "abc"
  1485. * </pre>
  1486. *
  1487. * @param str the String to get the leftmost characters from, may be null
  1488. * @param len the length of the required String, must be zero or positive
  1489. * @return the leftmost characters, <code>null</code> if null String input
  1490. */
  1491. public static String left(String str, int len) {
  1492. if (str == null) {
  1493. return null;
  1494. }
  1495. if (len < 0) {
  1496. return EMPTY;
  1497. }
  1498. if (str.length() <= len) {
  1499. return str;
  1500. } else {
  1501. return str.substring(0, len);
  1502. }
  1503. }
  1504. /**
  1505. * <p>Gets the rightmost <code>len</code> characters of a String.</p>
  1506. *
  1507. * <p>If <code>len</code> characters are not available, or the String
  1508. * is <code>null</code>, the String will be returned without an
  1509. * an exception. An exception is thrown if len is negative.</p>
  1510. *
  1511. * <pre>
  1512. * StringUtils.right(null, *) = null
  1513. * StringUtils.right(*, -ve) = ""
  1514. * StringUtils.right("", *) = ""
  1515. * StringUtils.right("abc", 0) = ""
  1516. * StringUtils.right("abc", 2) = "bc"
  1517. * StringUtils.right("abc", 4) = "abc"
  1518. * </pre>
  1519. *
  1520. * @param str the String to get the rightmost characters from, may be null
  1521. * @param len the length of the required String, must be zero or positive
  1522. * @return the rightmost characters, <code>null</code> if null String input
  1523. */
  1524. public static String right(String str, int len) {
  1525. if (str == null) {
  1526. return null;
  1527. }
  1528. if (len < 0) {
  1529. return EMPTY;
  1530. }
  1531. if (str.length() <= len) {
  1532. return str;
  1533. } else {
  1534. return str.substring(str.length() - len);
  1535. }
  1536. }
  1537. /**
  1538. * <p>Gets <code>len</code> characters from the middle of a String.</p>
  1539. *
  1540. * <p>If <code>len</code> characters are not available, the remainder
  1541. * of the String will be returned without an exception. If the
  1542. * String is <code>null</code>, <code>null</code> will be returned.
  1543. * An exception is thrown if len is negative.</p>
  1544. *
  1545. * <pre>
  1546. * StringUtils.mid(null, *, *) = null
  1547. * StringUtils.mid(*, *, -ve) = ""
  1548. * StringUtils.mid("", 0, *) = ""
  1549. * StringUtils.mid("abc", 0, 2) = "ab"
  1550. * StringUtils.mid("abc", 0, 4) = "abc"
  1551. * StringUtils.mid("abc", 2, 4) = "c"
  1552. * StringUtils.mid("abc", 4, 2) = ""
  1553. * StringUtils.mid("abc", -2, 2) = "ab"
  1554. * </pre>
  1555. *
  1556. * @param str the String to get the characters from, may be null
  1557. * @param pos the position to start from, negative treated as zero
  1558. * @param len the length of the required String, must be zero or positive
  1559. * @return the middle characters, <code>null</code> if null String input
  1560. */
  1561. public static String mid(String str, int pos, int len) {
  1562. if (str == null) {
  1563. return null;
  1564. }
  1565. if (len < 0 || pos > str.length()) {
  1566. return EMPTY;
  1567. }
  1568. if (pos < 0) {
  1569. pos = 0;
  1570. }
  1571. if (str.length() <= (pos + len)) {
  1572. return str.substring(pos);
  1573. } else {
  1574. return str.substring(pos, pos + len);
  1575. }
  1576. }
  1577. // SubStringAfter/SubStringBefore
  1578. //-----------------------------------------------------------------------
  1579. /**
  1580. * <p>Gets the substring before the first occurance of a separator.
  1581. * The separator is not returned.</p>
  1582. *
  1583. * <p>A <code>null</code> string input will return <code>null</code>.
  1584. * An empty ("") string input will return the empty string.
  1585. * A <code>null</code> separator will return the input string.</p>
  1586. *
  1587. * <pre>
  1588. * StringUtils.substringBefore(null, *) = null
  1589. * StringUtils.substringBefore("", *) = ""
  1590. * StringUtils.substringBefore("abc", "a") = ""
  1591. * StringUtils.substringBefore("abcba", "b") = "a"
  1592. * StringUtils.substringBefore("abc", "c") = "ab"
  1593. * StringUtils.substringBefore("abc", "d") = "abc"
  1594. * StringUtils.substringBefore("abc", "") = ""
  1595. * StringUtils.substringBefore("abc", null) = "abc"
  1596. * </pre>
  1597. *
  1598. * @param str the String to get a substring from, may be null
  1599. * @param separator the String to search for, may be null
  1600. * @return the substring before the first occurance of the separator,
  1601. * <code>null</code> if null String input
  1602. * @since 2.0
  1603. */
  1604. public static String substringBefore(String str, String separator) {
  1605. if (str == null || separator == null || str.length() == 0) {
  1606. return str;
  1607. }
  1608. if (separator.length() == 0) {
  1609. return EMPTY;
  1610. }
  1611. int pos = str.indexOf(separator);
  1612. if (pos == -1) {
  1613. return str;
  1614. }
  1615. return str.substring(0, pos);
  1616. }
  1617. /**
  1618. * <p>Gets the substring after the first occurance of a separator.
  1619. * The separator is not returned.</p>
  1620. *
  1621. * <p>A <code>null</code> string input will return <code>null</code>.
  1622. * An empty ("") string input will return the empty string.
  1623. * A <code>null</code> separator will return the empty string if the
  1624. * input string is not <code>null</code>.</p>
  1625. *
  1626. * <pre>
  1627. * StringUtils.substringAfter(null, *) = null
  1628. * StringUtils.substringAfter("", *) = ""
  1629. * StringUtils.substringAfter(*, null) = ""
  1630. * StringUtils.substringAfter("abc", "a") = "bc"
  1631. * StringUtils.substringAfter("abcba", "b") = "cba"
  1632. * StringUtils.substringAfter("abc", "c") = ""
  1633. * StringUtils.substringAfter("abc", "d") = ""
  1634. * StringUtils.substringAfter("abc", "") = "abc"
  1635. * </pre>
  1636. *
  1637. * @param str the String to get a substring from, may be null
  1638. * @param separator the String to search for, may be null
  1639. * @return the substring after the first occurance of the separator,
  1640. * <code>null</code> if null String input
  1641. * @since 2.0
  1642. */
  1643. public static String substringAfter(String str, String separator) {
  1644. if (str == null || str.length() == 0) {
  1645. return str;
  1646. }
  1647. if (separator == null) {
  1648. return EMPTY;
  1649. }
  1650. int pos = str.indexOf(separator);
  1651. if (pos == -1) {
  1652. return EMPTY;
  1653. }
  1654. return str.substring(pos + separator.length());
  1655. }
  1656. /**
  1657. * <p>Gets the substring before the last occurance of a separator.
  1658. * The separator is not returned.</p>
  1659. *
  1660. * <p>A <code>null</code> string input will return <code>null</code>.
  1661. * An empty ("") string input will return the empty string.
  1662. * An empty or <code>null</code> separator will return the input string.</p>
  1663. *
  1664. * <pre>
  1665. * StringUtils.substringBeforeLast(null, *) = null
  1666. * StringUtils.substringBeforeLast("", *) = ""
  1667. * StringUtils.substringBeforeLast("abcba", "b") = "abc"
  1668. * StringUtils.substringBeforeLast("abc", "c") = "ab"
  1669. * StringUtils.substringBeforeLast("a", "a") = ""
  1670. * StringUtils.substringBeforeLast("a", "z") = "a"
  1671. * StringUtils.substringBeforeLast("a", null) = "a"
  1672. * StringUtils.substringBeforeLast("a", "") = "a"
  1673. * </pre>
  1674. *
  1675. * @param str the String to get a substring from, may be null
  1676. * @param separator the String to search for, may be null
  1677. * @return the substring before the last occurance of the separator,
  1678. * <code>null</code> if null String input
  1679. * @since 2.0
  1680. */
  1681. public static String substringBeforeLast(String str, String separator) {
  1682. if (str == null || separator == null || str.length() == 0 || separator.length() == 0) {
  1683. return str;
  1684. }
  1685. int pos = str.lastIndexOf(separator);
  1686. if (pos == -1) {
  1687. return str;
  1688. }
  1689. return str.substring(0, pos);
  1690. }
  1691. /**
  1692. * <p>Gets the substring after the last occurance of a separator.
  1693. * The separator is not returned.</p>
  1694. *
  1695. * <p>A <code>null</code> string input will return <code>null</code>.
  1696. * An empty ("") string input will return the empty string.
  1697. * An empty or <code>null</code> separator will return the empty string if
  1698. * the input string is not <code>null</code>.</p>
  1699. *
  1700. * <pre>
  1701. * StringUtils.substringAfterLast(null, *) = null
  1702. * StringUtils.substringAfterLast("", *) = ""
  1703. * StringUtils.substringAfterLast(*, "") = ""
  1704. * StringUtils.substringAfterLast(*, null) = ""
  1705. * StringUtils.substringAfterLast("abc", "a") = "bc"
  1706. * StringUtils.substringAfterLast("abcba", "b") = "a"
  1707. * StringUtils.substringAfterLast("abc", "c") = ""
  1708. * StringUtils.substringAfterLast("a", "a") = ""
  1709. * StringUtils.substringAfterLast("a", "z") = ""
  1710. * </pre>
  1711. *
  1712. * @param str the String to get a substring from, may be null
  1713. * @param separator the String to search for, may be null
  1714. * @return the substring after the last occurance of the separator,
  1715. * <code>null</code> if null String input
  1716. * @since 2.0
  1717. */
  1718. public static String substringAfterLast(String str, String separator) {
  1719. if (str == null || str.length() == 0) {
  1720. return str;
  1721. }
  1722. if (separator == null || separator.length() == 0) {
  1723. return EMPTY;
  1724. }
  1725. int pos = str.lastIndexOf(separator);
  1726. if (pos == -1 || pos == (str.length() - separator.length())) {
  1727. return EMPTY;
  1728. }
  1729. return str.substring(pos + separator.length());
  1730. }
  1731. // Substring between
  1732. //-----------------------------------------------------------------------
  1733. /**
  1734. * <p>Gets the String that is nested in between two instances of the
  1735. * same String.</p>
  1736. *
  1737. * <p>A <code>null</code> input String returns <code>null</code>.
  1738. * A <code>null</code> tag returns <code>null</code>.</p>
  1739. *
  1740. * <pre>
  1741. * StringUtils.substringBetween(null, *) = null
  1742. * StringUtils.substringBetween("", "") = ""
  1743. * StringUtils.substringBetween("", "tag") = null
  1744. * StringUtils.substringBetween("tagabctag", null) = null
  1745. * StringUtils.substringBetween("tagabctag", "") = ""
  1746. * StringUtils.substringBetween("tagabctag", "tag") = "abc"
  1747. * </pre>
  1748. *
  1749. * @param str the String containing the substring, may be null
  1750. * @param tag the String before and after the substring, may be null
  1751. * @return the substring, <code>null</code> if no match
  1752. * @since 2.0
  1753. */
  1754. public static String substringBetween(String str, String tag) {
  1755. return substringBetween(str, tag, tag);
  1756. }
  1757. /**
  1758. * <p>Gets the String that is nested in between two Strings.
  1759. * Only the first match is returned.</p>
  1760. *
  1761. * <p>A <code>null</code> input String returns <code>null</code>.
  1762. * A <code>null</code> open/close returns <code>null</code> (no match).
  1763. * An empty ("") open/close returns an empty string.</p>
  1764. *
  1765. * <pre>
  1766. * StringUtils.substringBetween(null, *, *) = null
  1767. * StringUtils.substringBetween("", "", "") = ""
  1768. * StringUtils.substringBetween("", "", "tag") = null
  1769. * StringUtils.substringBetween("", "tag", "tag") = null
  1770. * StringUtils.substringBetween("yabcz", null, null) = null
  1771. * StringUtils.substringBetween("yabcz", "", "") = ""
  1772. * StringUtils.substringBetween("yabcz", "y", "z") = "abc"
  1773. * StringUtils.substringBetween("yabczyabcz", "y", "z") = "abc"
  1774. * </pre>
  1775. *
  1776. * @param str the String containing the substring, may be null
  1777. * @param open the String before the substring, may be null
  1778. * @param close the String after the substring, may be null
  1779. * @return the substring, <code>null</code> if no match
  1780. * @since 2.0
  1781. */
  1782. public static String substringBetween(String str, String open, String close) {
  1783. if (str == null || open == null || close == null) {
  1784. return null;
  1785. }
  1786. int start = str.indexOf(open);
  1787. if (start != -1) {
  1788. int end = str.indexOf(close, start + open.length());
  1789. if (end != -1) {
  1790. return str.substring(start + open.length(), end);
  1791. }
  1792. }
  1793. return null;
  1794. }
  1795. // Nested extraction
  1796. //-----------------------------------------------------------------------
  1797. /**
  1798. * <p>Gets the String that is nested in between two instances of the
  1799. * same String.</p>
  1800. *
  1801. * <p>A <code>null</code> input String returns <code>null</code>.
  1802. * A <code>null</code> tag returns <code>null</code>.</p>
  1803. *
  1804. * <pre>
  1805. * StringUtils.getNestedString(null, *) = null
  1806. * StringUtils.getNestedString("", "") = ""
  1807. * StringUtils.getNestedString("", "tag") = null
  1808. * StringUtils.getNestedString("tagabctag", null) = null
  1809. * StringUtils.getNestedString("tagabctag", "") = ""
  1810. * StringUtils.getNestedString("tagabctag", "tag") = "abc"
  1811. * </pre>
  1812. *
  1813. * @param str the String containing nested-string, may be null
  1814. * @param tag the String before and after nested-string, may be null
  1815. * @return the nested String, <code>null</code> if no match
  1816. * @deprecated Use the better named {@link #substringBetween(String, String)}.
  1817. * Method will be removed in Commons Lang 3.0.
  1818. */
  1819. public static String getNestedString(String str, String tag) {
  1820. return substringBetween(str, tag, tag);
  1821. }
  1822. /**
  1823. * <p>Gets the String that is nested in between two Strings.
  1824. * Only the first match is returned.</p>
  1825. *
  1826. * <p>A <code>null</code> input String returns <code>null</code>.
  1827. * A <code>null</code> open/close returns <code>null</code> (no match).
  1828. * An empty ("") open/close returns an empty string.</p>
  1829. *
  1830. * <pre>
  1831. * StringUtils.getNestedString(null, *, *) = null
  1832. * StringUtils.getNestedString("", "", "") = ""
  1833. * StringUtils.getNestedString("", "", "tag") = null
  1834. * StringUtils.getNestedString("", "tag", "tag") = null
  1835. * StringUtils.getNestedString("yabcz", null, null) = null
  1836. * StringUtils.getNestedString("yabcz", "", "") = ""
  1837. * StringUtils.getNestedString("yabcz", "y", "z") = "abc"
  1838. * StringUtils.getNestedString("yabczyabcz", "y", "z") = "abc"
  1839. * </pre>
  1840. *
  1841. * @param str the String containing nested-string, may be null
  1842. * @param open the String before nested-string, may be null
  1843. * @param close the String after nested-string, may be null
  1844. * @return the nested String, <code>null</code> if no match
  1845. * @deprecated Use the better named {@link #substringBetween(String, String, String)}.
  1846. * Method will be removed in Commons Lang 3.0.
  1847. */
  1848. public static String getNestedString(String str, String open, String close) {
  1849. return substringBetween(str, open, close);
  1850. }
  1851. // Splitting
  1852. //-----------------------------------------------------------------------
  1853. /**
  1854. * <p>Splits the provided text into an array, using whitespace as the
  1855. * separator.
  1856. * Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
  1857. *
  1858. * <p>The separator is not included in the returned String array.
  1859. * Adjacent separators are treated as one separator.</p>
  1860. *
  1861. * <p>A <code>null</code> input String returns <code>null</code>.</p>
  1862. *
  1863. * <pre>
  1864. * StringUtils.split(null) = null
  1865. * StringUtils.split("") = []
  1866. * StringUtils.split("abc def") = ["abc", "def"]
  1867. * StringUtils.split("abc def") = ["abc", "def"]
  1868. * StringUtils.split(" abc ") = ["abc"]
  1869. * </pre>
  1870. *
  1871. * @param str the String to parse, may be null
  1872. * @return an array of parsed Strings, <code>null</code> if null String input
  1873. */
  1874. public static String[] split(String str) {
  1875. return split(str, null, -1);
  1876. }
  1877. /**
  1878. * <p>Splits the provided text into an array, separator specified.
  1879. * This is an alternative to using StringTokenizer.</p>
  1880. *
  1881. * <p>The separator is not included in the returned String array.
  1882. * Adjacent separators are treated as one separator.</p>
  1883. *
  1884. * <p>A <code>null</code> input String returns <code>null</code>.</p>
  1885. *
  1886. * <pre>
  1887. * StringUtils.split(null, *) = null
  1888. * StringUtils.split("", *) = []
  1889. * StringUtils.split("a.b.c", '.') = ["a", "b", "c"]
  1890. * StringUtils.split("a..b.c", '.') = ["a", "b", "c"]
  1891. * StringUtils.split("a:b:c", '.') = ["a:b:c"]
  1892. * StringUtils.split("a\tb\nc", null) = ["a", "b", "c"]
  1893. * StringUtils.split("a b c", ' ') = ["a", "b", "c"]
  1894. * </pre>
  1895. *
  1896. * @param str the String to parse, may be null
  1897. * @param separatorChar the character used as the delimiter,
  1898. * <code>null</code> splits on whitespace
  1899. * @return an array of parsed Strings, <code>null</code> if null String input
  1900. * @since 2.0
  1901. */
  1902. public static String[] split(String str, char separatorChar) {
  1903. // Performance tuned for 2.0 (JDK1.4)
  1904. if (str == null) {
  1905. return null;
  1906. }
  1907. int len = str.length();
  1908. if (len == 0) {
  1909. return ArrayUtils.EMPTY_STRING_ARRAY;
  1910. }
  1911. List list = new ArrayList();
  1912. int i =0, start = 0;
  1913. boolean match = false;
  1914. while (i < len) {
  1915. if (str.charAt(i) == separatorChar) {
  1916. if (match) {
  1917. list.add(str.substring(start, i));
  1918. match = false;
  1919. }
  1920. start = ++i;
  1921. continue;
  1922. }
  1923. match = true;
  1924. i++;
  1925. }
  1926. if (match) {
  1927. list.add(str.substring(start, i));
  1928. }
  1929. return (String[]) list.toArray(new String[list.size()]);
  1930. }
  1931. /**
  1932. * <p>Splits the provided text into an array, separators specified.
  1933. * This is an alternative to using StringTokenizer.</p>
  1934. *
  1935. * <p>The separator is not included in the returned String array.
  1936. * Adjacent separators are treated as one separator.</p>
  1937. *
  1938. * <p>A <code>null</code> input String returns <code>null</code>.
  1939. * A <code>null</code> separatorChars splits on whitespace.</p>
  1940. *
  1941. * <pre>
  1942. * StringUtils.split(null, *) = null
  1943. * StringUtils.split("", *) = []
  1944. * StringUtils.split("abc def", null) = ["abc", "def"]
  1945. * StringUtils.split("abc def", " ") = ["abc", "def"]
  1946. * StringUtils.split("abc def", " ") = ["abc", "def"]
  1947. * StringUtils.split("ab:cd:ef", ":") = ["ab", "cd", "ef"]
  1948. * </pre>
  1949. *
  1950. * @param str the String to parse, may be null
  1951. * @param separatorChars the characters used as the delimiters,
  1952. * <code>null</code> splits on whitespace
  1953. * @return an array of parsed Strings, <code>null</code> if null String input
  1954. */
  1955. public static String[] split(String str, String separatorChars) {
  1956. return split(str, separatorChars, -1);
  1957. }
  1958. /**
  1959. * <p>Splits the provided text into an array, separators specified.
  1960. * This is an alternative to using StringTokenizer.</p>
  1961. *
  1962. * <p>The separator is not included in the returned String array.
  1963. * Adjacent separators are treated as one separator.</p>
  1964. *
  1965. * <p>A <code>null</code> input String returns <code>null</code>.
  1966. * A <code>null</code> separatorChars splits on whitespace.</p>
  1967. *
  1968. * <pre>
  1969. * StringUtils.split(null, *, *) = null
  1970. * StringUtils.split("", *, *) = []
  1971. * StringUtils.split("ab de fg", null, 0) = ["ab", "cd", "ef"]
  1972. * StringUtils.split("ab de fg", null, 0) = ["ab", "cd", "ef"]
  1973. * StringUtils.split("ab:cd:ef", ":", 0) = ["ab", "cd", "ef"]
  1974. * StringUtils.split("ab:cd:ef", ":", 2) = ["ab", "cdef"]
  1975. * </pre>
  1976. *
  1977. * @param str the String to parse, may be null
  1978. * @param separatorChars the characters used as the delimiters,
  1979. * <code>null</code> splits on whitespace
  1980. * @param max the maximum number of elements to include in the
  1981. * array. A zero or negative value implies no limit
  1982. * @return an array of parsed Strings, <code>null</code> if null String input
  1983. */
  1984. public static String[] split(String str, String separatorChars, int max) {
  1985. // Performance tuned for 2.0 (JDK1.4)
  1986. // Direct code is quicker than StringTokenizer.
  1987. // Also, StringTokenizer uses isSpace() not isWhitespace()
  1988. if (str == null) {
  1989. return null;
  1990. }
  1991. int len = str.length();
  1992. if (len == 0) {
  1993. return ArrayUtils.EMPTY_STRING_ARRAY;
  1994. }
  1995. List list = new ArrayList();
  1996. int sizePlus1 = 1;
  1997. int i =0, start = 0;
  1998. boolean match = false;
  1999. if (separatorChars == null) {
  2000. // Null separator means use whitespace
  2001. while (i < len) {
  2002. if (Character.isWhitespace(str.charAt(i))) {
  2003. if (match) {
  2004. if (sizePlus1++ == max) {
  2005. i = len;
  2006. }
  2007. list.add(str.substring(start, i));
  2008. match = false;
  2009. }
  2010. start = ++i;
  2011. continue;
  2012. }
  2013. match = true;
  2014. i++;
  2015. }
  2016. } else if (separatorChars.length() == 1) {
  2017. // Optimise 1 character case
  2018. char sep = separatorChars.charAt(0);
  2019. while (i < len) {
  2020. if (str.charAt(i) == sep) {
  2021. if (match) {
  2022. if (sizePlus1++ == max) {
  2023. i = len;
  2024. }
  2025. list.add(str.substring(start, i));
  2026. match = false;
  2027. }
  2028. start = ++i;
  2029. continue;
  2030. }
  2031. match = true;
  2032. i++;
  2033. }
  2034. } else {
  2035. // standard case
  2036. while (i < len) {
  2037. if (separatorChars.indexOf(str.charAt(i)) >= 0) {
  2038. if (match) {
  2039. if (sizePlus1++ == max) {
  2040. i = len;
  2041. }
  2042. list.add(str.substring(start, i));
  2043. match = false;
  2044. }
  2045. start = ++i;
  2046. continue;
  2047. }
  2048. match = true;
  2049. i++;
  2050. }
  2051. }
  2052. if (match) {
  2053. list.add(str.substring(start, i));
  2054. }
  2055. return (String[]) list.toArray(new String[list.size()]);
  2056. }
  2057. // Joining
  2058. //-----------------------------------------------------------------------
  2059. /**
  2060. * <p>Concatenates elements of an array into a single String.
  2061. * Null objects or empty strings within the array are represented by
  2062. * empty strings.</p>
  2063. *
  2064. * <pre>
  2065. * StringUtils.concatenate(null) = null
  2066. * StringUtils.concatenate([]) = ""
  2067. * StringUtils.concatenate([null]) = ""
  2068. * StringUtils.concatenate(["a", "b", "c"]) = "abc"
  2069. * StringUtils.concatenate([null, "", "a"]) = "a"
  2070. * </pre>
  2071. *
  2072. * @param array the array of values to concatenate, may be null
  2073. * @return the concatenated String, <code>null</code> if null array input
  2074. * @deprecated Use the better named {@link #join(Object[])} instead.
  2075. * Method will be removed in Commons Lang 3.0.
  2076. */
  2077. public static String concatenate(Object[] array) {
  2078. return join(array, null);
  2079. }
  2080. /**
  2081. * <p>Joins the elements of the provided array into a single String
  2082. * containing the provided list of elements.</p>
  2083. *
  2084. * <p>No separator is added to the joined String.
  2085. * Null objects or empty strings within the array are represented by
  2086. * empty strings.</p>
  2087. *
  2088. * <pre>
  2089. * StringUtils.join(null) = null
  2090. * StringUtils.join([]) = ""
  2091. * StringUtils.join([null]) = ""
  2092. * StringUtils.join(["a", "b", "c"]) = "abc"
  2093. * StringUtils.join([null, "", "a"]) = "a"
  2094. * </pre>
  2095. *
  2096. * @param array the array of values to join together, may be null
  2097. * @return the joined String, <code>null</code> if null array input
  2098. * @since 2.0
  2099. */
  2100. public static String join(Object[] array) {
  2101. return join(array, null);
  2102. }
  2103. /**
  2104. * <p>Joins the elements of the provided array into a single String
  2105. * containing the provided list of elements.</p>
  2106. *
  2107. * <p>No delimiter is added before or after the list.
  2108. * Null objects or empty strings within the array are represented by
  2109. * empty strings.</p>
  2110. *
  2111. * <pre>
  2112. * StringUtils.join(null, *) = null
  2113. * StringUtils.join([], *) = ""
  2114. * StringUtils.join([null], *) = ""
  2115. * StringUtils.join(["a", "b", "c"], ';') = "a;b;c"
  2116. * StringUtils.join(["a", "b", "c"], null) = "abc"
  2117. * StringUtils.join([null, "", "a"], ';') = ";;a"
  2118. * </pre>
  2119. *
  2120. * @param array the array of values to join together, may be null
  2121. * @param separator the separator character to use
  2122. * @return the joined String, <code>null</code> if null array input
  2123. * @since 2.0
  2124. */
  2125. public static String join(Object[] array, char separator) {
  2126. if (array == null) {
  2127. return null;
  2128. }
  2129. int arraySize = array.length;
  2130. int bufSize = (arraySize == 0 ? 0 : ((array[0] == null ? 16 : array[0].toString().length()) + 1) * arraySize);
  2131. StringBuffer buf = new StringBuffer(bufSize);
  2132. for (int i = 0; i < arraySize; i++) {
  2133. if (i > 0) {
  2134. buf.append(separator);
  2135. }
  2136. if (array[i] != null) {
  2137. buf.append(array[i]);
  2138. }
  2139. }
  2140. return buf.toString();
  2141. }
  2142. /**
  2143. * <p>Joins the elements of the provided array into a single String
  2144. * containing the provided list of elements.</p>
  2145. *
  2146. * <p>No delimiter is added before or after the list.
  2147. * A <code>null</code> separator is the same as an empty String ("").
  2148. * Null objects or empty strings within the array are represented by
  2149. * empty strings.</p>
  2150. *
  2151. * <pre>
  2152. * StringUtils.join(null, *) = null
  2153. * StringUtils.join([], *) = ""
  2154. * StringUtils.join([null], *) = ""
  2155. * StringUtils.join(["a", "b", "c"], "--") = "a--b--c"
  2156. * StringUtils.join(["a", "b", "c"], null) = "abc"
  2157. * StringUtils.join(["a", "b", "c"], "") = "abc"
  2158. * StringUtils.join([null, "", "a"], ',') = ",,a"
  2159. * </pre>
  2160. *
  2161. * @param array the array of values to join together, may be null
  2162. * @param separator the separator character to use, null treated as ""
  2163. * @return the joined String, <code>null</code> if null array input
  2164. */
  2165. public static String join(Object[] array, String separator) {
  2166. if (array == null) {
  2167. return null;
  2168. }
  2169. if (separator == null) {
  2170. separator = EMPTY;
  2171. }
  2172. int arraySize = array.length;
  2173. // ArraySize == 0: Len = 0
  2174. // ArraySize > 0: Len = NofStrings *(len(firstString) + len(separator))
  2175. // (Assuming that all Strings are roughly equally long)
  2176. int bufSize
  2177. = ((arraySize == 0) ? 0
  2178. : arraySize * ((array[0] == null ? 16 : array[0].toString().length())
  2179. + ((separator != null) ? separator.length(): 0)));
  2180. StringBuffer buf = new StringBuffer(bufSize);
  2181. for (int i = 0; i < arraySize; i++) {
  2182. if ((separator != null) && (i > 0)) {
  2183. buf.append(separator);
  2184. }
  2185. if (array[i] != null) {
  2186. buf.append(array[i]);
  2187. }
  2188. }
  2189. return buf.toString();
  2190. }
  2191. /**
  2192. * <p>Joins the elements of the provided <code>Iterator</code> into
  2193. * a single String containing the provided elements.</p>
  2194. *
  2195. * <p>No delimiter is added before or after the list. Null objects or empty
  2196. * strings within the iteration are represented by empty strings.</p>
  2197. *
  2198. * <p>See the examples here: {@link #join(Object[],char)}. </p>
  2199. *
  2200. * @param iterator the <code>Iterator</code> of values to join together, may be null
  2201. * @param separator the separator character to use
  2202. * @return the joined String, <code>null</code> if null iterator input
  2203. * @since 2.0
  2204. */
  2205. public static String join(Iterator iterator, char separator) {
  2206. if (iterator == null) {
  2207. return null;
  2208. }
  2209. StringBuffer buf = new StringBuffer(256); // Java default is 16, probably too small
  2210. while (iterator.hasNext()) {
  2211. Object obj = iterator.next();
  2212. if (obj != null) {
  2213. buf.append(obj);
  2214. }
  2215. if (iterator.hasNext()) {
  2216. buf.append(separator);
  2217. }
  2218. }
  2219. return buf.toString();
  2220. }
  2221. /**
  2222. * <p>Joins the elements of the provided <code>Iterator</code> into
  2223. * a single String containing the provided elements.</p>
  2224. *
  2225. * <p>No delimiter is added before or after the list.
  2226. * A <code>null</code> separator is the same as an empty String ("").</p>
  2227. *
  2228. * <p>See the examples here: {@link #join(Object[],String)}. </p>
  2229. *
  2230. * @param iterator the <code>Iterator</code> of values to join together, may be null
  2231. * @param separator the separator character to use, null treated as ""
  2232. * @return the joined String, <code>null</code> if null iterator input
  2233. */
  2234. public static String join(Iterator iterator, String separator) {
  2235. if (iterator == null) {
  2236. return null;
  2237. }
  2238. StringBuffer buf = new StringBuffer(256); // Java default is 16, probably too small
  2239. while (iterator.hasNext()) {
  2240. Object obj = iterator.next();
  2241. if (obj != null) {
  2242. buf.append(obj);
  2243. }
  2244. if ((separator != null) && iterator.hasNext()) {
  2245. buf.append(separator);
  2246. }
  2247. }
  2248. return buf.toString();
  2249. }
  2250. // Delete
  2251. //-----------------------------------------------------------------------
  2252. /**
  2253. * <p>Deletes all 'space' characters from a String as defined by
  2254. * {@link Character#isSpace(char)}.</p>
  2255. *
  2256. * <p>This is the only StringUtils method that uses the
  2257. * <code>isSpace</code> definition. You are advised to use
  2258. * {@link #deleteWhitespace(String)} instead as whitespace is much
  2259. * better localized.</p>
  2260. *
  2261. * <pre>
  2262. * StringUtils.deleteSpaces(null) = null
  2263. * StringUtils.deleteSpaces("") = ""
  2264. * StringUtils.deleteSpaces("abc") = "abc"
  2265. * StringUtils.deleteSpaces(" \t abc \n ") = "abc"
  2266. * StringUtils.deleteSpaces("ab c") = "abc"
  2267. * StringUtils.deleteSpaces("a\nb\tc ") = "abc"
  2268. * </pre>
  2269. *
  2270. * <p>Spaces are defined as <code>{' ', '\t', '\r', '\n', '\b'}</code>
  2271. * in line with the deprecated <code>isSpace</code> method.</p>
  2272. *
  2273. * @param str the String to delete spaces from, may be null
  2274. * @return the String without 'spaces', <code>null</code> if null String input
  2275. * @deprecated Use the better localized {@link #deleteWhitespace(String)}.
  2276. * Method will be removed in Commons Lang 3.0.
  2277. */
  2278. public static String deleteSpaces(String str) {
  2279. if (str == null) {
  2280. return null;
  2281. }
  2282. return CharSetUtils.delete(str, " \t\r\n\b");
  2283. }
  2284. /**
  2285. * <p>Deletes all whitespaces from a String as defined by
  2286. * {@link Character#isWhitespace(char)}.</p>
  2287. *
  2288. * <pre>
  2289. * StringUtils.deleteWhitespace(null) = null
  2290. * StringUtils.deleteWhitespace("") = ""
  2291. * StringUtils.deleteWhitespace("abc") = "abc"
  2292. * StringUtils.deleteWhitespace(" ab c ") = "abc"
  2293. * </pre>
  2294. *
  2295. * @param str the String to delete whitespace from, may be null
  2296. * @return the String without whitespaces, <code>null</code> if null String input
  2297. */
  2298. public static String deleteWhitespace(String str) {
  2299. if (str == null) {
  2300. return null;
  2301. }
  2302. int sz = str.length();
  2303. StringBuffer buffer = new StringBuffer(sz);
  2304. for (int i = 0; i < sz; i++) {
  2305. if (!Character.isWhitespace(str.charAt(i))) {
  2306. buffer.append(str.charAt(i));
  2307. }
  2308. }
  2309. return buffer.toString();
  2310. }
  2311. // Replacing
  2312. //-----------------------------------------------------------------------
  2313. /**
  2314. * <p>Replaces a String with another String inside a larger String, once.</p>
  2315. *
  2316. * <p>A <code>null</code> reference passed to this method is a no-op.</p>
  2317. *
  2318. * <pre>
  2319. * StringUtils.replaceOnce(null, *, *) = null
  2320. * StringUtils.replaceOnce("", *, *) = ""
  2321. * StringUtils.replaceOnce("aba", null, null) = "aba"
  2322. * StringUtils.replaceOnce("aba", null, null) = "aba"
  2323. * StringUtils.replaceOnce("aba", "a", null) = "aba"
  2324. * StringUtils.replaceOnce("aba", "a", "") = "aba"
  2325. * StringUtils.replaceOnce("aba", "a", "z") = "zba"
  2326. * </pre>
  2327. *
  2328. * @see #replace(String text, String repl, String with, int max)
  2329. * @param text text to search and replace in, may be null
  2330. * @param repl the String to search for, may be null
  2331. * @param with the String to replace with, may be null
  2332. * @return the text with any replacements processed,
  2333. * <code>null</code> if null String input
  2334. */
  2335. public static String replaceOnce(String text, String repl, String with) {
  2336. return replace(text, repl, with, 1);
  2337. }
  2338. /**
  2339. * <p>Replaces all occurances of a String within another String.</p>
  2340. *
  2341. * <p>A <code>null</code> reference passed to this method is a no-op.</p>
  2342. *
  2343. * <pre>
  2344. * StringUtils.replace(null, *, *) = null
  2345. * StringUtils.replace("", *, *) = ""
  2346. * StringUtils.replace("aba", null, null) = "aba"
  2347. * StringUtils.replace("aba", null, null) = "aba"
  2348. * StringUtils.replace("aba", "a", null) = "aba"
  2349. * StringUtils.replace("aba", "a", "") = "aba"
  2350. * StringUtils.replace("aba", "a", "z") = "zbz"
  2351. * </pre>
  2352. *
  2353. * @see #replace(String text, String repl, String with, int max)
  2354. * @param text text to search and replace in, may be null
  2355. * @param repl the String to search for, may be null
  2356. * @param with the String to replace with, may be null
  2357. * @return the text with any replacements processed,
  2358. * <code>null</code> if null String input
  2359. */
  2360. public static String replace(String text, String repl, String with) {
  2361. return replace(text, repl, with, -1);
  2362. }
  2363. /**
  2364. * <p>Replaces a String with another String inside a larger String,
  2365. * for the first <code>max</code> values of the search String.</p>
  2366. *
  2367. * <p>A <code>null</code> reference passed to this method is a no-op.</p>
  2368. *
  2369. * <pre>
  2370. * StringUtils.replace(null, *, *, *) = null
  2371. * StringUtils.replace("", *, *, *) = ""
  2372. * StringUtils.replace("abaa", null, null, 1) = "abaa"
  2373. * StringUtils.replace("abaa", null, null, 1) = "abaa"
  2374. * StringUtils.replace("abaa", "a", null, 1) = "abaa"
  2375. * StringUtils.replace("abaa", "a", "", 1) = "abaa"
  2376. * StringUtils.replace("abaa", "a", "z", 0) = "abaa"
  2377. * StringUtils.replace("abaa", "a", "z", 1) = "zbaa"
  2378. * StringUtils.replace("abaa", "a", "z", 2) = "zbza"
  2379. * StringUtils.replace("abaa", "a", "z", -1) = "zbzz"
  2380. * </pre>
  2381. *
  2382. * @param text text to search and replace in, may be null
  2383. * @param repl the String to search for, may be null
  2384. * @param with the String to replace with, may be null
  2385. * @param max maximum number of values to replace, or <code>-1</code> if no maximum
  2386. * @return the text with any replacements processed,
  2387. * <code>null</code> if null String input
  2388. */
  2389. public static String replace(String text, String repl, String with, int max) {
  2390. if (text == null || repl == null || with == null || repl.length() == 0 || max == 0) {
  2391. return text;
  2392. }
  2393. StringBuffer buf = new StringBuffer(text.length());
  2394. int start = 0, end = 0;
  2395. while ((end = text.indexOf(repl, start)) != -1) {
  2396. buf.append(text.substring(start, end)).append(with);
  2397. start = end + repl.length();
  2398. if (--max == 0) {
  2399. break;
  2400. }
  2401. }
  2402. buf.append(text.substring(start));
  2403. return buf.toString();
  2404. }
  2405. // Replace, character based
  2406. //-----------------------------------------------------------------------
  2407. /**
  2408. * <p>Replaces all occurrances of a character in a String with another.
  2409. * This is a null-safe version of {@link String#replace(char, char)}.</p>
  2410. *
  2411. * <p>A <code>null</code> string input returns <code>null</code>.
  2412. * An empty ("") string input returns an empty string.</p>
  2413. *
  2414. * <pre>
  2415. * StringUtils.replaceChars(null, *, *) = null
  2416. * StringUtils.replaceChars("", *, *) = ""
  2417. * StringUtils.replaceChars("abcba", 'b', 'y') = "aycya"
  2418. * StringUtils.replaceChars("abcba", 'z', 'y') = "abcba"
  2419. * </pre>
  2420. *
  2421. * @param str String to replace characters in, may be null
  2422. * @param searchChar the character to search for, may be null
  2423. * @param replaceChar the character to replace, may be null
  2424. * @return modified String, <code>null</code> if null string input
  2425. * @since 2.0
  2426. */
  2427. public static String replaceChars(String str, char searchChar, char replaceChar) {
  2428. if (str == null) {
  2429. return null;
  2430. }
  2431. return str.replace(searchChar, replaceChar);
  2432. }
  2433. /**
  2434. * <p>Replaces multiple characters in a String in one go.
  2435. * This method can also be used to delete characters.</p>
  2436. *
  2437. * <p>For example:<br />
  2438. * <code>replaceChars("hello", "ho", "jy") = jelly</code>.</p>
  2439. *
  2440. * <p>A <code>null</code> string input returns <code>null</code>.
  2441. * An empty ("") string input returns an empty string.
  2442. * A null or empty set of search characters returns the input string.</p>
  2443. *
  2444. * <p>The length of the search characters should normally equal the length
  2445. * of the replace characters.
  2446. * If the search characters is longer, then the extra search characters
  2447. * are deleted.
  2448. * If the search characters is shorter, then the extra replace characters
  2449. * are ignored.</p>
  2450. *
  2451. * <pre>
  2452. * StringUtils.replaceChars(null, *, *) = null
  2453. * StringUtils.replaceChars("", *, *) = ""
  2454. * StringUtils.replaceChars("abc", null, *) = "abc"
  2455. * StringUtils.replaceChars("abc", "", *) = "abc"
  2456. * StringUtils.replaceChars("abc", "b", null) = "ac"
  2457. * StringUtils.replaceChars("abc", "b", "") = "ac"
  2458. * StringUtils.replaceChars("abcba", "bc", "yz") = "ayzya"
  2459. * StringUtils.replaceChars("abcba", "bc", "y") = "ayya"
  2460. * StringUtils.replaceChars("abcba", "bc", "yzx") = "ayzya"
  2461. * </pre>
  2462. *
  2463. * @param str String to replace characters in, may be null
  2464. * @param searchChars a set of characters to search for, may be null
  2465. * @param replaceChars a set of characters to replace, may be null
  2466. * @return modified String, <code>null</code> if null string input
  2467. * @since 2.0
  2468. */
  2469. public static String replaceChars(String str, String searchChars, String replaceChars) {
  2470. if (str == null || str.length() == 0 || searchChars == null || searchChars.length()== 0) {
  2471. return str;
  2472. }
  2473. char[] chars = str.toCharArray();
  2474. int len = chars.length;
  2475. boolean modified = false;
  2476. for (int i = 0, isize = searchChars.length(); i < isize; i++) {
  2477. char searchChar = searchChars.charAt(i);
  2478. if (replaceChars == null || i >= replaceChars.length()) {
  2479. // delete
  2480. int pos = 0;
  2481. for (int j = 0; j < len; j++) {
  2482. if (chars[j] != searchChar) {
  2483. chars[pos++] = chars[j];
  2484. } else {
  2485. modified = true;
  2486. }
  2487. }
  2488. len = pos;
  2489. } else {
  2490. // replace
  2491. for (int j = 0; j < len; j++) {
  2492. if (chars[j] == searchChar) {
  2493. chars[j] = replaceChars.charAt(i);
  2494. modified = true;
  2495. }
  2496. }
  2497. }
  2498. }
  2499. if (modified == false) {
  2500. return str;
  2501. }
  2502. return new String(chars, 0, len);
  2503. }
  2504. // Overlay
  2505. //-----------------------------------------------------------------------
  2506. /**
  2507. * <p>Overlays part of a String with another String.</p>
  2508. *
  2509. * <pre>
  2510. * StringUtils.overlayString(null, *, *, *) = NullPointerException
  2511. * StringUtils.overlayString(*, null, *, *) = NullPointerException
  2512. * StringUtils.overlayString("", "abc", 0, 0) = "abc"
  2513. * StringUtils.overlayString("abcdef", null, 2, 4) = "abef"
  2514. * StringUtils.overlayString("abcdef", "", 2, 4) = "abef"
  2515. * StringUtils.overlayString("abcdef", "zzzz", 2, 4) = "abzzzzef"
  2516. * StringUtils.overlayString("abcdef", "zzzz", 4, 2) = "abcdzzzzcdef"
  2517. * StringUtils.overlayString("abcdef", "zzzz", -1, 4) = IndexOutOfBoundsException
  2518. * StringUtils.overlayString("abcdef", "zzzz", 2, 8) = IndexOutOfBoundsException
  2519. * </pre>
  2520. *
  2521. * @param text the String to do overlaying in, may be null
  2522. * @param overlay the String to overlay, may be null
  2523. * @param start the position to start overlaying at, must be valid
  2524. * @param end the position to stop overlaying before, must be valid
  2525. * @return overlayed String, <code>null</code> if null String input
  2526. * @throws NullPointerException if text or overlay is null
  2527. * @throws IndexOutOfBoundsException if either position is invalid
  2528. * @deprecated Use better named {@link #overlay(String, String, int, int)} instead.
  2529. * Method will be removed in Commons Lang 3.0.
  2530. */
  2531. public static String overlayString(String text, String overlay, int start, int end) {
  2532. return new StringBuffer(start + overlay.length() + text.length() - end + 1)
  2533. .append(text.substring(0, start))
  2534. .append(overlay)
  2535. .append(text.substring(end))
  2536. .toString();
  2537. }
  2538. /**
  2539. * <p>Overlays part of a String with another String.</p>
  2540. *
  2541. * <p>A <code>null</code> string input returns <code>null</code>.
  2542. * A negative index is treated as zero.
  2543. * An index greater than the string length is treated as the string length.
  2544. * The start index is always the smaller of the two indices.</p>
  2545. *
  2546. * <pre>
  2547. * StringUtils.overlay(null, *, *, *) = null
  2548. * StringUtils.overlay("", "abc", 0, 0) = "abc"
  2549. * StringUtils.overlay("abcdef", null, 2, 4) = "abef"
  2550. * StringUtils.overlay("abcdef", "", 2, 4) = "abef"
  2551. * StringUtils.overlay("abcdef", "", 4, 2) = "abef"
  2552. * StringUtils.overlay("abcdef", "zzzz", 2, 4) = "abzzzzef"
  2553. * StringUtils.overlay("abcdef", "zzzz", 4, 2) = "abzzzzef"
  2554. * StringUtils.overlay("abcdef", "zzzz", -1, 4) = "zzzzef"
  2555. * StringUtils.overlay("abcdef", "zzzz", 2, 8) = "abzzzz"
  2556. * StringUtils.overlay("abcdef", "zzzz", -2, -3) = "zzzzabcdef"
  2557. * StringUtils.overlay("abcdef", "zzzz", 8, 10) = "abcdefzzzz"
  2558. * </pre>
  2559. *
  2560. * @param str the String to do overlaying in, may be null
  2561. * @param overlay the String to overlay, may be null
  2562. * @param start the position to start overlaying at
  2563. * @param end the position to stop overlaying before
  2564. * @return overlayed String, <code>null</code> if null String input
  2565. * @since 2.0
  2566. */
  2567. public static String overlay(String str, String overlay, int start, int end) {
  2568. if (str == null) {
  2569. return null;
  2570. }
  2571. if (overlay == null) {
  2572. overlay = EMPTY;
  2573. }
  2574. int len = str.length();
  2575. if (start < 0) {
  2576. start = 0;
  2577. }
  2578. if (start > len) {
  2579. start = len;
  2580. }
  2581. if (end < 0) {
  2582. end = 0;
  2583. }
  2584. if (end > len) {
  2585. end = len;
  2586. }
  2587. if (start > end) {
  2588. int temp = start;
  2589. start = end;
  2590. end = temp;
  2591. }
  2592. return new StringBuffer(len + start - end + overlay.length() + 1)
  2593. .append(str.substring(0, start))
  2594. .append(overlay)
  2595. .append(str.substring(end))
  2596. .toString();
  2597. }
  2598. // Chomping
  2599. //-----------------------------------------------------------------------
  2600. /**
  2601. * <p>Removes one newline from end of a String if it's there,
  2602. * otherwise leave it alone. A newline is "<code>\n</code>",
  2603. * "<code>\r</code>", or "<code>\r\n</code>".</p>
  2604. *
  2605. * <p>NOTE: This method changed in 2.0.
  2606. * It now more closely matches Perl chomp.</p>
  2607. *
  2608. * <pre>
  2609. * StringUtils.chomp(null) = null
  2610. * StringUtils.chomp("") = ""
  2611. * StringUtils.chomp("abc \r") = "abc "
  2612. * StringUtils.chomp("abc\n") = "abc"
  2613. * StringUtils.chomp("abc\r\n") = "abc"
  2614. * StringUtils.chomp("abc\r\n\r\n") = "abc\r\n"
  2615. * StringUtils.chomp("abc\n\r") = "abc\n"
  2616. * StringUtils.chomp("abc\n\rabc") = "abc\n\rabc"
  2617. * StringUtils.chomp("\r") = ""
  2618. * StringUtils.chomp("\n") = ""
  2619. * StringUtils.chomp("\r\n") = ""
  2620. * </pre>
  2621. *
  2622. * @param str the String to chomp a newline from, may be null
  2623. * @return String without newline, <code>null</code> if null String input
  2624. */
  2625. public static String chomp(String str) {
  2626. if (str == null || str.length() == 0) {
  2627. return str;
  2628. }
  2629. if (str.length() == 1) {
  2630. char ch = str.charAt(0);
  2631. if (ch == '\r' || ch == '\n') {
  2632. return EMPTY;
  2633. } else {
  2634. return str;
  2635. }
  2636. }
  2637. int lastIdx = str.length() - 1;
  2638. char last = str.charAt(lastIdx);
  2639. if (last == '\n') {
  2640. if (str.charAt(lastIdx - 1) == '\r') {
  2641. lastIdx--;
  2642. }
  2643. } else if (last == '\r') {
  2644. } else {
  2645. lastIdx++;
  2646. }
  2647. return str.substring(0, lastIdx);
  2648. }
  2649. /**
  2650. * <p>Removes <code>separator</code> from the end of
  2651. * <code>str</code> if it's there, otherwise leave it alone.</p>
  2652. *
  2653. * <p>NOTE: This method changed in version 2.0.
  2654. * It now more closely matches Perl chomp.
  2655. * For the previous behavior, use {@link #substringBeforeLast(String, String)}.
  2656. * This method uses {@link String#endsWith(String)}.</p>
  2657. *
  2658. * <pre>
  2659. * StringUtils.chomp(null, *) = null
  2660. * StringUtils.chomp("", *) = ""
  2661. * StringUtils.chomp("foobar", "bar") = "foo"
  2662. * StringUtils.chomp("foobar", "baz") = "foobar"
  2663. * StringUtils.chomp("foo", "foo") = ""
  2664. * StringUtils.chomp("foo ", "foo") = "foo"
  2665. * StringUtils.chomp(" foo", "foo") = " "
  2666. * StringUtils.chomp("foo", "foooo") = "foo"
  2667. * StringUtils.chomp("foo", "") = "foo"
  2668. * StringUtils.chomp("foo", null) = "foo"
  2669. * </pre>
  2670. *
  2671. * @param str the String to chomp from, may be null
  2672. * @param separator separator String, may be null
  2673. * @return String without trailing separator, <code>null</code> if null String input
  2674. */
  2675. public static String chomp(String str, String separator) {
  2676. if (str == null || str.length() == 0 || separator == null) {
  2677. return str;
  2678. }
  2679. if (str.endsWith(separator)) {
  2680. return str.substring(0, str.length() - separator.length());
  2681. }
  2682. return str;
  2683. }
  2684. /**
  2685. * <p>Remove any "\n" if and only if it is at the end
  2686. * of the supplied String.</p>
  2687. *
  2688. * @param str the String to chomp from, must not be null
  2689. * @return String without chomped ending
  2690. * @throws NullPointerException if str is <code>null</code>
  2691. * @deprecated Use {@link #chomp(String)} instead.
  2692. * Method will be removed in Commons Lang 3.0.
  2693. */
  2694. public static String chompLast(String str) {
  2695. return chompLast(str, "\n");
  2696. }
  2697. /**
  2698. * <p>Remove a value if and only if the String ends with that value.</p>
  2699. *
  2700. * @param str the String to chomp from, must not be null
  2701. * @param sep the String to chomp, must not be null
  2702. * @return String without chomped ending
  2703. * @throws NullPointerException if str or sep is <code>null</code>
  2704. * @deprecated Use {@link #chomp(String,String)} instead.
  2705. * Method will be removed in Commons Lang 3.0.
  2706. */
  2707. public static String chompLast(String str, String sep) {
  2708. if (str.length() == 0) {
  2709. return str;
  2710. }
  2711. String sub = str.substring(str.length() - sep.length());
  2712. if (sep.equals(sub)) {
  2713. return str.substring(0, str.length() - sep.length());
  2714. } else {
  2715. return str;
  2716. }
  2717. }
  2718. /**
  2719. * <p>Remove everything and return the last value of a supplied String, and
  2720. * everything after it from a String.</p>
  2721. *
  2722. * @param str the String to chomp from, must not be null
  2723. * @param sep the String to chomp, must not be null
  2724. * @return String chomped
  2725. * @throws NullPointerException if str or sep is <code>null</code>
  2726. * @deprecated Use {@link #substringAfterLast(String, String)} instead
  2727. * (although this doesn't include the separator)
  2728. * Method will be removed in Commons Lang 3.0.
  2729. */
  2730. public static String getChomp(String str, String sep) {
  2731. int idx = str.lastIndexOf(sep);
  2732. if (idx == str.length() - sep.length()) {
  2733. return sep;
  2734. } else if (idx != -1) {
  2735. return str.substring(idx);
  2736. } else {
  2737. return EMPTY;
  2738. }
  2739. }
  2740. /**
  2741. * <p>Remove the first value of a supplied String, and everything before it
  2742. * from a String.</p>
  2743. *
  2744. * @param str the String to chomp from, must not be null
  2745. * @param sep the String to chomp, must not be null
  2746. * @return String without chomped beginning
  2747. * @throws NullPointerException if str or sep is <code>null</code>
  2748. * @deprecated Use {@link #substringAfter(String,String)} instead.
  2749. * Method will be removed in Commons Lang 3.0.
  2750. */
  2751. public static String prechomp(String str, String sep) {
  2752. int idx = str.indexOf(sep);
  2753. if (idx != -1) {
  2754. return str.substring(idx + sep.length());
  2755. } else {
  2756. return str;
  2757. }
  2758. }
  2759. /**
  2760. * <p>Remove and return everything before the first value of a
  2761. * supplied String from another String.</p>
  2762. *
  2763. * @param str the String to chomp from, must not be null
  2764. * @param sep the String to chomp, must not be null
  2765. * @return String prechomped
  2766. * @throws NullPointerException if str or sep is <code>null</code>
  2767. * @deprecated Use {@link #substringBefore(String,String)} instead
  2768. * (although this doesn't include the separator).
  2769. * Method will be removed in Commons Lang 3.0.
  2770. */
  2771. public static String getPrechomp(String str, String sep) {
  2772. int idx = str.indexOf(sep);
  2773. if (idx != -1) {
  2774. return str.substring(0, idx + sep.length());
  2775. } else {
  2776. return EMPTY;
  2777. }
  2778. }
  2779. // Chopping
  2780. //-----------------------------------------------------------------------
  2781. /**
  2782. * <p>Remove the last character from a String.</p>
  2783. *
  2784. * <p>If the String ends in <code>\r\n</code>, then remove both
  2785. * of them.</p>
  2786. *
  2787. * <pre>
  2788. * StringUtils.chop(null) = null
  2789. * StringUtils.chop("") = ""
  2790. * StringUtils.chop("abc \r") = "abc "
  2791. * StringUtils.chop("abc\n") = "abc"
  2792. * StringUtils.chop("abc\r\n") = "abc"
  2793. * StringUtils.chop("abc") = "ab"
  2794. * StringUtils.chop("abc\nabc") = "abc\nab"
  2795. * StringUtils.chop("a") = ""
  2796. * StringUtils.chop("\r") = ""
  2797. * StringUtils.chop("\n") = ""
  2798. * StringUtils.chop("\r\n") = ""
  2799. * </pre>
  2800. *
  2801. * @param str the String to chop last character from, may be null
  2802. * @return String without last character, <code>null</code> if null String input
  2803. */
  2804. public static String chop(String str) {
  2805. if (str == null) {
  2806. return null;
  2807. }
  2808. int strLen = str.length();
  2809. if (strLen < 2) {
  2810. return EMPTY;
  2811. }
  2812. int lastIdx = strLen - 1;
  2813. String ret = str.substring(0, lastIdx);
  2814. char last = str.charAt(lastIdx);
  2815. if (last == '\n') {
  2816. if (ret.charAt(lastIdx - 1) == '\r') {
  2817. return ret.substring(0, lastIdx - 1);
  2818. }
  2819. }
  2820. return ret;
  2821. }
  2822. /**
  2823. * <p>Removes <code>\n</code> from end of a String if it's there.
  2824. * If a <code>\r</code> precedes it, then remove that too.</p>
  2825. *
  2826. * @param str the String to chop a newline from, must not be null
  2827. * @return String without newline
  2828. * @throws NullPointerException if str is <code>null</code>
  2829. * @deprecated Use {@link #chomp(String)} instead.
  2830. * Method will be removed in Commons Lang 3.0.
  2831. */
  2832. public static String chopNewline(String str) {
  2833. int lastIdx = str.length() - 1;
  2834. if (lastIdx <= 0) {
  2835. return EMPTY;
  2836. }
  2837. char last = str.charAt(lastIdx);
  2838. if (last == '\n') {
  2839. if (str.charAt(lastIdx - 1) == '\r') {
  2840. lastIdx--;
  2841. }
  2842. } else {
  2843. lastIdx++;
  2844. }
  2845. return str.substring(0, lastIdx);
  2846. }
  2847. // Conversion
  2848. //-----------------------------------------------------------------------
  2849. /**
  2850. * <p>Escapes any values it finds into their String form.</p>
  2851. *
  2852. * <p>So a tab becomes the characters <code>'\\'</code> and
  2853. * <code>'t'</code>.</p>
  2854. *
  2855. * <p>As of Lang 2.0, this calls {@link StringEscapeUtils#escapeJava(String)}
  2856. * behind the scenes.
  2857. * </p>
  2858. * @see StringEscapeUtils#escapeJava(java.lang.String)
  2859. * @param str String to escape values in
  2860. * @return String with escaped values
  2861. * @throws NullPointerException if str is <code>null</code>
  2862. * @deprecated Use {@link StringEscapeUtils#escapeJava(String)}
  2863. * This method will be removed in Commons Lang 3.0
  2864. */
  2865. public static String escape(String str) {
  2866. return StringEscapeUtils.escapeJava(str);
  2867. }
  2868. // Padding
  2869. //-----------------------------------------------------------------------
  2870. /**
  2871. * <p>Repeat a String <code>repeat</code> times to form a
  2872. * new String.</p>
  2873. *
  2874. * <pre>
  2875. * StringUtils.repeat(null, 2) = null
  2876. * StringUtils.repeat("", 0) = ""
  2877. * StringUtils.repeat("", 2) = ""
  2878. * StringUtils.repeat("a", 3) = "aaa"
  2879. * StringUtils.repeat("ab", 2) = "abab"
  2880. * StringUtils.repeat("a", -2) = ""
  2881. * </pre>
  2882. *
  2883. * @param str the String to repeat, may be null
  2884. * @param repeat number of times to repeat str, negative treated as zero
  2885. * @return a new String consisting of the original String repeated,
  2886. * <code>null</code> if null String input
  2887. */
  2888. public static String repeat(String str, int repeat) {
  2889. // Performance tuned for 2.0 (JDK1.4)
  2890. if (str == null) {
  2891. return null;
  2892. }
  2893. if (repeat <= 0) {
  2894. return EMPTY;
  2895. }
  2896. int inputLength = str.length();
  2897. if (repeat == 1 || inputLength == 0) {
  2898. return str;
  2899. }
  2900. if (inputLength == 1 && repeat <= PAD_LIMIT) {
  2901. return padding(repeat, str.charAt(0));
  2902. }
  2903. int outputLength = inputLength * repeat;
  2904. switch (inputLength) {
  2905. case 1:
  2906. char ch = str.charAt(0);
  2907. char[] output1 = new char[outputLength];
  2908. for (int i = repeat - 1; i >= 0; i--) {
  2909. output1[i] = ch;
  2910. }
  2911. return new String(output1);
  2912. case 2:
  2913. char ch0 = str.charAt(0);
  2914. char ch1 = str.charAt(1);
  2915. char[] output2 = new char[outputLength];
  2916. for (int i = repeat * 2 - 2; i >= 0; i--,i--) {
  2917. output2[i] = ch0;
  2918. output2[i + 1] = ch1;
  2919. }
  2920. return new String(output2);
  2921. default:
  2922. StringBuffer buf = new StringBuffer(outputLength);
  2923. for (int i = 0; i < repeat; i++) {
  2924. buf.append(str);
  2925. }
  2926. return buf.toString();
  2927. }
  2928. }
  2929. /**
  2930. * <p>Returns padding using the specified delimiter repeated
  2931. * to a given length.</p>
  2932. *
  2933. * <pre>
  2934. * StringUtils.padding(0, 'e') = ""
  2935. * StringUtils.padding(3, 'e') = "eee"
  2936. * StringUtils.padding(-2, 'e') = IndexOutOfBoundsException
  2937. * </pre>
  2938. *
  2939. * @param repeat number of times to repeat delim
  2940. * @param padChar character to repeat
  2941. * @return String with repeated character
  2942. * @throws IndexOutOfBoundsException if <code>repeat < 0</code>
  2943. */
  2944. private static String padding(int repeat, char padChar) {
  2945. // be careful of synchronization in this method
  2946. // we are assuming that get and set from an array index is atomic
  2947. String pad = PADDING[padChar];
  2948. if (pad == null) {
  2949. pad = String.valueOf(padChar);
  2950. }
  2951. while (pad.length() < repeat) {
  2952. pad = pad.concat(pad);
  2953. }
  2954. PADDING[padChar] = pad;
  2955. return pad.substring(0, repeat);
  2956. }
  2957. /**
  2958. * <p>Right pad a String with spaces (' ').</p>
  2959. *
  2960. * <p>The String is padded to the size of <code>size</code>.</p>
  2961. *
  2962. * <pre>
  2963. * StringUtils.rightPad(null, *) = null
  2964. * StringUtils.rightPad("", 3) = " "
  2965. * StringUtils.rightPad("bat", 3) = "bat"
  2966. * StringUtils.rightPad("bat", 5) = "bat "
  2967. * StringUtils.rightPad("bat", 1) = "bat"
  2968. * StringUtils.rightPad("bat", -1) = "bat"
  2969. * </pre>
  2970. *
  2971. * @param str the String to pad out, may be null
  2972. * @param size the size to pad to
  2973. * @return right padded String or original String if no padding is necessary,
  2974. * <code>null</code> if null String input
  2975. */
  2976. public static String rightPad(String str, int size) {
  2977. return rightPad(str, size, ' ');
  2978. }
  2979. /**
  2980. * <p>Right pad a String with a specified character.</p>
  2981. *
  2982. * <p>The String is padded to the size of <code>size</code>.</p>
  2983. *
  2984. * <pre>
  2985. * StringUtils.rightPad(null, *, *) = null
  2986. * StringUtils.rightPad("", 3, 'z') = "zzz"
  2987. * StringUtils.rightPad("bat", 3, 'z') = "bat"
  2988. * StringUtils.rightPad("bat", 5, 'z') = "batzz"
  2989. * StringUtils.rightPad("bat", 1, 'z') = "bat"
  2990. * StringUtils.rightPad("bat", -1, 'z') = "bat"
  2991. * </pre>
  2992. *
  2993. * @param str the String to pad out, may be null
  2994. * @param size the size to pad to
  2995. * @param padChar the character to pad with
  2996. * @return right padded String or original String if no padding is necessary,
  2997. * <code>null</code> if null String input
  2998. * @since 2.0
  2999. */
  3000. public static String rightPad(String str, int size, char padChar) {
  3001. if (str == null) {
  3002. return null;
  3003. }
  3004. int pads = size - str.length();
  3005. if (pads <= 0) {
  3006. return str; // returns original String when possible
  3007. }
  3008. if (pads > PAD_LIMIT) {
  3009. return rightPad(str, size, String.valueOf(padChar));
  3010. }
  3011. return str.concat(padding(pads, padChar));
  3012. }
  3013. /**
  3014. * <p>Right pad a String with a specified String.</p>
  3015. *
  3016. * <p>The String is padded to the size of <code>size</code>.</p>
  3017. *
  3018. * <pre>
  3019. * StringUtils.rightPad(null, *, *) = null
  3020. * StringUtils.rightPad("", 3, "z") = "zzz"
  3021. * StringUtils.rightPad("bat", 3, "yz") = "bat"
  3022. * StringUtils.rightPad("bat", 5, "yz") = "batyz"
  3023. * StringUtils.rightPad("bat", 8, "yz") = "batyzyzy"
  3024. * StringUtils.rightPad("bat", 1, "yz") = "bat"
  3025. * StringUtils.rightPad("bat", -1, "yz") = "bat"
  3026. * StringUtils.rightPad("bat", 5, null) = "bat "
  3027. * StringUtils.rightPad("bat", 5, "") = "bat "
  3028. * </pre>
  3029. *
  3030. * @param str the String to pad out, may be null
  3031. * @param size the size to pad to
  3032. * @param padStr the String to pad with, null or empty treated as single space
  3033. * @return right padded String or original String if no padding is necessary,
  3034. * <code>null</code> if null String input
  3035. */
  3036. public static String rightPad(String str, int size, String padStr) {
  3037. if (str == null) {
  3038. return null;
  3039. }
  3040. if (padStr == null || padStr.length() == 0) {
  3041. padStr = " ";
  3042. }
  3043. int padLen = padStr.length();
  3044. int strLen = str.length();
  3045. int pads = size - strLen;
  3046. if (pads <= 0) {
  3047. return str; // returns original String when possible
  3048. }
  3049. if (padLen == 1 && pads <= PAD_LIMIT) {
  3050. return rightPad(str, size, padStr.charAt(0));
  3051. }
  3052. if (pads == padLen) {
  3053. return str.concat(padStr);
  3054. } else if (pads < padLen) {
  3055. return str.concat(padStr.substring(0, pads));
  3056. } else {
  3057. char[] padding = new char[pads];
  3058. char[] padChars = padStr.toCharArray();
  3059. for (int i = 0; i < pads; i++) {
  3060. padding[i] = padChars[i % padLen];
  3061. }
  3062. return str.concat(new String(padding));
  3063. }
  3064. }
  3065. /**
  3066. * <p>Left pad a String with spaces (' ').</p>
  3067. *
  3068. * <p>The String is padded to the size of <code>size<code>.</p>
  3069. *
  3070. * <pre>
  3071. * StringUtils.leftPad(null, *) = null
  3072. * StringUtils.leftPad("", 3) = " "
  3073. * StringUtils.leftPad("bat", 3) = "bat"
  3074. * StringUtils.leftPad("bat", 5) = " bat"
  3075. * StringUtils.leftPad("bat", 1) = "bat"
  3076. * StringUtils.leftPad("bat", -1) = "bat"
  3077. * </pre>
  3078. *
  3079. * @param str the String to pad out, may be null
  3080. * @param size the size to pad to
  3081. * @return left padded String or original String if no padding is necessary,
  3082. * <code>null</code> if null String input
  3083. */
  3084. public static String leftPad(String str, int size) {
  3085. return leftPad(str, size, ' ');
  3086. }
  3087. /**
  3088. * <p>Left pad a String with a specified character.</p>
  3089. *
  3090. * <p>Pad to a size of <code>size</code>.</p>
  3091. *
  3092. * <pre>
  3093. * StringUtils.leftPad(null, *, *) = null
  3094. * StringUtils.leftPad("", 3, 'z') = "zzz"
  3095. * StringUtils.leftPad("bat", 3, 'z') = "bat"
  3096. * StringUtils.leftPad("bat", 5, 'z') = "zzbat"
  3097. * StringUtils.leftPad("bat", 1, 'z') = "bat"
  3098. * StringUtils.leftPad("bat", -1, 'z') = "bat"
  3099. * </pre>
  3100. *
  3101. * @param str the String to pad out, may be null
  3102. * @param size the size to pad to
  3103. * @param padChar the character to pad with
  3104. * @return left padded String or original String if no padding is necessary,
  3105. * <code>null</code> if null String input
  3106. * @since 2.0
  3107. */
  3108. public static String leftPad(String str, int size, char padChar) {
  3109. if (str == null) {
  3110. return null;
  3111. }
  3112. int pads = size - str.length();
  3113. if (pads <= 0) {
  3114. return str; // returns original String when possible
  3115. }
  3116. if (pads > PAD_LIMIT) {
  3117. return leftPad(str, size, String.valueOf(padChar));
  3118. }
  3119. return padding(pads, padChar).concat(str);
  3120. }
  3121. /**
  3122. * <p>Left pad a String with a specified String.</p>
  3123. *
  3124. * <p>Pad to a size of <code>size</code>.</p>
  3125. *
  3126. * <pre>
  3127. * StringUtils.leftPad(null, *, *) = null
  3128. * StringUtils.leftPad("", 3, "z") = "zzz"
  3129. * StringUtils.leftPad("bat", 3, "yz") = "bat"
  3130. * StringUtils.leftPad("bat", 5, "yz") = "yzbat"
  3131. * StringUtils.leftPad("bat", 8, "yz") = "yzyzybat"
  3132. * StringUtils.leftPad("bat", 1, "yz") = "bat"
  3133. * StringUtils.leftPad("bat", -1, "yz") = "bat"
  3134. * StringUtils.leftPad("bat", 5, null) = " bat"
  3135. * StringUtils.leftPad("bat", 5, "") = " bat"
  3136. * </pre>
  3137. *
  3138. * @param str the String to pad out, may be null
  3139. * @param size the size to pad to
  3140. * @param padStr the String to pad with, null or empty treated as single space
  3141. * @return left padded String or original String if no padding is necessary,
  3142. * <code>null</code> if null String input
  3143. */
  3144. public static String leftPad(String str, int size, String padStr) {
  3145. if (str == null) {
  3146. return null;
  3147. }
  3148. if (padStr == null || padStr.length() == 0) {
  3149. padStr = " ";
  3150. }
  3151. int padLen = padStr.length();
  3152. int strLen = str.length();
  3153. int pads = size - strLen;
  3154. if (pads <= 0) {
  3155. return str; // returns original String when possible
  3156. }
  3157. if (padLen == 1 && pads <= PAD_LIMIT) {
  3158. return leftPad(str, size, padStr.charAt(0));
  3159. }
  3160. if (pads == padLen) {
  3161. return padStr.concat(str);
  3162. } else if (pads < padLen) {
  3163. return padStr.substring(0, pads).concat(str);
  3164. } else {
  3165. char[] padding = new char[pads];
  3166. char[] padChars = padStr.toCharArray();
  3167. for (int i = 0; i < pads; i++) {
  3168. padding[i] = padChars[i % padLen];
  3169. }
  3170. return new String(padding).concat(str);
  3171. }
  3172. }
  3173. // Centering
  3174. //-----------------------------------------------------------------------
  3175. /**
  3176. * <p>Centers a String in a larger String of size <code>size</code>
  3177. * using the space character (' ').<p>
  3178. *
  3179. * <p>If the size is less than the String length, the String is returned.
  3180. * A <code>null</code> String returns <code>null</code>.
  3181. * A negative size is treated as zero.</p>
  3182. *
  3183. * <p>Equivalent to <code>center(str, size, " ")</code>.</p>
  3184. *
  3185. * <pre>
  3186. * StringUtils.center(null, *) = null
  3187. * StringUtils.center("", 4) = " "
  3188. * StringUtils.center("ab", -1) = "ab"
  3189. * StringUtils.center("ab", 4) = " ab "
  3190. * StringUtils.center("abcd", 2) = "abcd"
  3191. * StringUtils.center("a", 4) = " a "
  3192. * </pre>
  3193. *
  3194. * @param str the String to center, may be null
  3195. * @param size the int size of new String, negative treated as zero
  3196. * @return centered String, <code>null</code> if null String input
  3197. */
  3198. public static String center(String str, int size) {
  3199. return center(str, size, ' ');
  3200. }
  3201. /**
  3202. * <p>Centers a String in a larger String of size <code>size</code>.
  3203. * Uses a supplied character as the value to pad the String with.</p>
  3204. *
  3205. * <p>If the size is less than the String length, the String is returned.
  3206. * A <code>null</code> String returns <code>null</code>.
  3207. * A negative size is treated as zero.</p>
  3208. *
  3209. * <pre>
  3210. * StringUtils.center(null, *, *) = null
  3211. * StringUtils.center("", 4, ' ') = " "
  3212. * StringUtils.center("ab", -1, ' ') = "ab"
  3213. * StringUtils.center("ab", 4, ' ') = " ab"
  3214. * StringUtils.center("abcd", 2, ' ') = "abcd"
  3215. * StringUtils.center("a", 4, ' ') = " a "
  3216. * StringUtils.center("a", 4, 'y') = "yayy"
  3217. * </pre>
  3218. *
  3219. * @param str the String to center, may be null
  3220. * @param size the int size of new String, negative treated as zero
  3221. * @param padChar the character to pad the new String with
  3222. * @return centered String, <code>null</code> if null String input
  3223. * @since 2.0
  3224. */
  3225. public static String center(String str, int size, char padChar) {
  3226. if (str == null || size <= 0) {
  3227. return str;
  3228. }
  3229. int strLen = str.length();
  3230. int pads = size - strLen;
  3231. if (pads <= 0) {
  3232. return str;
  3233. }
  3234. str = leftPad(str, strLen + pads / 2, padChar);
  3235. str = rightPad(str, size, padChar);
  3236. return str;
  3237. }
  3238. /**
  3239. * <p>Centers a String in a larger String of size <code>size</code>.
  3240. * Uses a supplied String as the value to pad the String with.</p>
  3241. *
  3242. * <p>If the size is less than the String length, the String is returned.
  3243. * A <code>null</code> String returns <code>null</code>.
  3244. * A negative size is treated as zero.</p>
  3245. *
  3246. * <pre>
  3247. * StringUtils.center(null, *, *) = null
  3248. * StringUtils.center("", 4, " ") = " "
  3249. * StringUtils.center("ab", -1, " ") = "ab"
  3250. * StringUtils.center("ab", 4, " ") = " ab"
  3251. * StringUtils.center("abcd", 2, " ") = "abcd"
  3252. * StringUtils.center("a", 4, " ") = " a "
  3253. * StringUtils.center("a", 4, "yz") = "yayz"
  3254. * StringUtils.center("abc", 7, null) = " abc "
  3255. * StringUtils.center("abc", 7, "") = " abc "
  3256. * </pre>
  3257. *
  3258. * @param str the String to center, may be null
  3259. * @param size the int size of new String, negative treated as zero
  3260. * @param padStr the String to pad the new String with, must not be null or empty
  3261. * @return centered String, <code>null</code> if null String input
  3262. * @throws IllegalArgumentException if padStr is <code>null</code> or empty
  3263. */
  3264. public static String center(String str, int size, String padStr) {
  3265. if (str == null || size <= 0) {
  3266. return str;
  3267. }
  3268. if (padStr == null || padStr.length() == 0) {
  3269. padStr = " ";
  3270. }
  3271. int strLen = str.length();
  3272. int pads = size - strLen;
  3273. if (pads <= 0) {
  3274. return str;
  3275. }
  3276. str = leftPad(str, strLen + pads / 2, padStr);
  3277. str = rightPad(str, size, padStr);
  3278. return str;
  3279. }
  3280. // Case conversion
  3281. //-----------------------------------------------------------------------
  3282. /**
  3283. * <p>Converts a String to upper case as per {@link String#toUpperCase()}.</p>
  3284. *
  3285. * <p>A <code>null</code> input String returns <code>null</code>.</p>
  3286. *
  3287. * <pre>
  3288. * StringUtils.upperCase(null) = null
  3289. * StringUtils.upperCase("") = ""
  3290. * StringUtils.upperCase("aBc") = "ABC"
  3291. * </pre>
  3292. *
  3293. * @param str the String to upper case, may be null
  3294. * @return the upper cased String, <code>null</code> if null String input
  3295. */
  3296. public static String upperCase(String str) {
  3297. if (str == null) {
  3298. return null;
  3299. }
  3300. return str.toUpperCase();
  3301. }
  3302. /**
  3303. * <p>Converts a String to lower case as per {@link String#toLowerCase()}.</p>
  3304. *
  3305. * <p>A <code>null</code> input String returns <code>null</code>.</p>
  3306. *
  3307. * <pre>
  3308. * StringUtils.lowerCase(null) = null
  3309. * StringUtils.lowerCase("") = ""
  3310. * StringUtils.lowerCase("aBc") = "abc"
  3311. * </pre>
  3312. *
  3313. * @param str the String to lower case, may be null
  3314. * @return the lower cased String, <code>null</code> if null String input
  3315. */
  3316. public static String lowerCase(String str) {
  3317. if (str == null) {
  3318. return null;
  3319. }
  3320. return str.toLowerCase();
  3321. }
  3322. /**
  3323. * <p>Capitalizes a String changing the first letter to title case as
  3324. * per {@link Character#toTitleCase(char)}. No other letters are changed.</p>
  3325. *
  3326. * <p>For a word based alorithm, see {@link WordUtils#capitalize(String)}.
  3327. * A <code>null</code> input String returns <code>null</code>.</p>
  3328. *
  3329. * <pre>
  3330. * StringUtils.capitalize(null) = null
  3331. * StringUtils.capitalize("") = ""
  3332. * StringUtils.capitalize("cat") = "Cat"
  3333. * StringUtils.capitalize("cAt") = "CAt"
  3334. * </pre>
  3335. *
  3336. * @param str the String to capitalize, may be null
  3337. * @return the capitalized String, <code>null</code> if null String input
  3338. * @see WordUtils#capitalize(String)
  3339. * @see #uncapitalize(String)
  3340. * @since 2.0
  3341. */
  3342. public static String capitalize(String str) {
  3343. int strLen;
  3344. if (str == null || (strLen = str.length()) == 0) {
  3345. return str;
  3346. }
  3347. return new StringBuffer(strLen)
  3348. .append(Character.toTitleCase(str.charAt(0)))
  3349. .append(str.substring(1))
  3350. .toString();
  3351. }
  3352. /**
  3353. * <p>Capitalizes a String changing the first letter to title case as
  3354. * per {@link Character#toTitleCase(char)}. No other letters are changed.</p>
  3355. *
  3356. * @param str the String to capitalize, may be null
  3357. * @return the capitalized String, <code>null</code> if null String input
  3358. * @deprecated Use the standardly named {@link #capitalize(String)}.
  3359. * Method will be removed in Commons Lang 3.0.
  3360. */
  3361. public static String capitalise(String str) {
  3362. return capitalize(str);
  3363. }
  3364. /**
  3365. * <p>Uncapitalizes a String changing the first letter to title case as
  3366. * per {@link Character#toLowerCase(char)}. No other letters are changed.</p>
  3367. *
  3368. * <p>For a word based alorithm, see {@link WordUtils#uncapitalize(String)}.
  3369. * A <code>null</code> input String returns <code>null</code>.</p>
  3370. *
  3371. * <pre>
  3372. * StringUtils.uncapitalize(null) = null
  3373. * StringUtils.uncapitalize("") = ""
  3374. * StringUtils.uncapitalize("Cat") = "cat"
  3375. * StringUtils.uncapitalize("CAT") = "cAT"
  3376. * </pre>
  3377. *
  3378. * @param str the String to uncapitalize, may be null
  3379. * @return the uncapitalized String, <code>null</code> if null String input
  3380. * @see WordUtils#uncapitalize(String)
  3381. * @see #capitalize(String)
  3382. * @since 2.0
  3383. */
  3384. public static String uncapitalize(String str) {
  3385. int strLen;
  3386. if (str == null || (strLen = str.length()) == 0) {
  3387. return str;
  3388. }
  3389. return new StringBuffer(strLen)
  3390. .append(Character.toLowerCase(str.charAt(0)))
  3391. .append(str.substring(1))
  3392. .toString();
  3393. }
  3394. /**
  3395. * <p>Uncapitalizes a String changing the first letter to title case as
  3396. * per {@link Character#toLowerCase(char)}. No other letters are changed.</p>
  3397. *
  3398. * @param str the String to uncapitalize, may be null
  3399. * @return the uncapitalized String, <code>null</code> if null String input
  3400. * @deprecated Use the standardly named {@link #uncapitalize(String)}.
  3401. * Method will be removed in Commons Lang 3.0.
  3402. */
  3403. public static String uncapitalise(String str) {
  3404. return uncapitalize(str);
  3405. }
  3406. /**
  3407. * <p>Swaps the case of a String changing upper and title case to
  3408. * lower case, and lower case to upper case.</p>
  3409. *
  3410. * <ul>
  3411. * <li>Upper case character converts to Lower case</li>
  3412. * <li>Title case character converts to Lower case</li>
  3413. * <li>Lower case character converts to Upper case</li>
  3414. * </ul>
  3415. *
  3416. * <p>For a word based alorithm, see {@link WordUtils#swapCase(String)}.
  3417. * A <code>null</code> input String returns <code>null</code>.</p>
  3418. *
  3419. * <pre>
  3420. * StringUtils.swapCase(null) = null
  3421. * StringUtils.swapCase("") = ""
  3422. * StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
  3423. * </pre>
  3424. *
  3425. * <p>NOTE: This method changed in Lang version 2.0.
  3426. * It no longer performs a word based alorithm.
  3427. * If you only use ASCII, you will notice no change.
  3428. * That functionality is available in WordUtils.</p>
  3429. *
  3430. * @param str the String to swap case, may be null
  3431. * @return the changed String, <code>null</code> if null String input
  3432. */
  3433. public static String swapCase(String str) {
  3434. int strLen;
  3435. if (str == null || (strLen = str.length()) == 0) {
  3436. return str;
  3437. }
  3438. StringBuffer buffer = new StringBuffer(strLen);
  3439. char ch = 0;
  3440. for (int i = 0; i < strLen; i++) {
  3441. ch = str.charAt(i);
  3442. if (Character.isUpperCase(ch)) {
  3443. ch = Character.toLowerCase(ch);
  3444. } else if (Character.isTitleCase(ch)) {
  3445. ch = Character.toLowerCase(ch);
  3446. } else if (Character.isLowerCase(ch)) {
  3447. ch = Character.toUpperCase(ch);
  3448. }
  3449. buffer.append(ch);
  3450. }
  3451. return buffer.toString();
  3452. }
  3453. /**
  3454. * <p>Capitalizes all the whitespace separated words in a String.
  3455. * Only the first letter of each word is changed.</p>
  3456. *
  3457. * <p>Whitespace is defined by {@link Character#isWhitespace(char)}.
  3458. * A <code>null</code> input String returns <code>null</code>.</p>
  3459. *
  3460. * @param str the String to capitalize, may be null
  3461. * @return capitalized String, <code>null</code> if null String input
  3462. * @deprecated Use the relocated {@link WordUtils#capitalize(String)}.
  3463. * Method will be removed in Commons Lang 3.0.
  3464. */
  3465. public static String capitaliseAllWords(String str) {
  3466. return WordUtils.capitalize(str);
  3467. }
  3468. // Count matches
  3469. //-----------------------------------------------------------------------
  3470. /**
  3471. * <p>Counts how many times the substring appears in the larger String.</p>
  3472. *
  3473. * <p>A <code>null</code> or empty ("") String input returns <code>0</code>.</p>
  3474. *
  3475. * <pre>
  3476. * StringUtils.countMatches(null, *) = 0
  3477. * StringUtils.countMatches("", *) = 0
  3478. * StringUtils.countMatches("abba", null) = 0
  3479. * StringUtils.countMatches("abba", "") = 0
  3480. * StringUtils.countMatches("abba", "a") = 2
  3481. * StringUtils.countMatches("abba", "ab") = 1
  3482. * StringUtils.countMatches("abba", "xxx") = 0
  3483. * </pre>
  3484. *
  3485. * @param str the String to check, may be null
  3486. * @param sub the substring to count, may be null
  3487. * @return the number of occurances, 0 if either String is <code>null</code>
  3488. */
  3489. public static int countMatches(String str, String sub) {
  3490. if (str == null || str.length() == 0 || sub == null || sub.length() == 0) {
  3491. return 0;
  3492. }
  3493. int count = 0;
  3494. int idx = 0;
  3495. while ((idx = str.indexOf(sub, idx)) != -1) {
  3496. count++;
  3497. idx += sub.length();
  3498. }
  3499. return count;
  3500. }
  3501. // Character Tests
  3502. //-----------------------------------------------------------------------
  3503. /**
  3504. * <p>Checks if the String contains only unicode letters.</p>
  3505. *
  3506. * <p><code>null</code> will return <code>false</code>.
  3507. * An empty String ("") will return <code>true</code>.</p>
  3508. *
  3509. * <pre>
  3510. * StringUtils.isAlpha(null) = false
  3511. * StringUtils.isAlpha("") = true
  3512. * StringUtils.isAlpha(" ") = false
  3513. * StringUtils.isAlpha("abc") = true
  3514. * StringUtils.isAlpha("ab2c") = false
  3515. * StringUtils.isAlpha("ab-c") = false
  3516. * </pre>
  3517. *
  3518. * @param str the String to check, may be null
  3519. * @return <code>true</code> if only contains letters, and is non-null
  3520. */
  3521. public static boolean isAlpha(String str) {
  3522. if (str == null) {
  3523. return false;
  3524. }
  3525. int sz = str.length();
  3526. for (int i = 0; i < sz; i++) {
  3527. if (Character.isLetter(str.charAt(i)) == false) {
  3528. return false;
  3529. }
  3530. }
  3531. return true;
  3532. }
  3533. /**
  3534. * <p>Checks if the String contains only unicode letters and
  3535. * space (' ').</p>
  3536. *
  3537. * <p><code>null</code> will return <code>false</code>
  3538. * An empty String ("") will return <code>true</code>.</p>
  3539. *
  3540. * <pre>
  3541. * StringUtils.isAlphaSpace(null) = false
  3542. * StringUtils.isAlphaSpace("") = true
  3543. * StringUtils.isAlphaSpace(" ") = true
  3544. * StringUtils.isAlphaSpace("abc") = true
  3545. * StringUtils.isAlphaSpace("ab c") = true
  3546. * StringUtils.isAlphaSpace("ab2c") = false
  3547. * StringUtils.isAlphaSpace("ab-c") = false
  3548. * </pre>
  3549. *
  3550. * @param str the String to check, may be null
  3551. * @return <code>true</code> if only contains letters and space,
  3552. * and is non-null
  3553. */
  3554. public static boolean isAlphaSpace(String str) {
  3555. if (str == null) {
  3556. return false;
  3557. }
  3558. int sz = str.length();
  3559. for (int i = 0; i < sz; i++) {
  3560. if ((Character.isLetter(str.charAt(i)) == false) &&
  3561. (str.charAt(i) != ' ')) {
  3562. return false;
  3563. }
  3564. }
  3565. return true;
  3566. }
  3567. /**
  3568. * <p>Checks if the String contains only unicode letters or digits.</p>
  3569. *
  3570. * <p><code>null</code> will return <code>false</code>.
  3571. * An empty String ("") will return <code>true</code>.</p>
  3572. *
  3573. * <pre>
  3574. * StringUtils.isAlphanumeric(null) = false
  3575. * StringUtils.isAlphanumeric("") = true
  3576. * StringUtils.isAlphanumeric(" ") = false
  3577. * StringUtils.isAlphanumeric("abc") = true
  3578. * StringUtils.isAlphanumeric("ab c") = false
  3579. * StringUtils.isAlphanumeric("ab2c") = true
  3580. * StringUtils.isAlphanumeric("ab-c") = false
  3581. * </pre>
  3582. *
  3583. * @param str the String to check, may be null
  3584. * @return <code>true</code> if only contains letters or digits,
  3585. * and is non-null
  3586. */
  3587. public static boolean isAlphanumeric(String str) {
  3588. if (str == null) {
  3589. return false;
  3590. }
  3591. int sz = str.length();
  3592. for (int i = 0; i < sz; i++) {
  3593. if (Character.isLetterOrDigit(str.charAt(i)) == false) {
  3594. return false;
  3595. }
  3596. }
  3597. return true;
  3598. }
  3599. /**
  3600. * <p>Checks if the String contains only unicode letters, digits
  3601. * or space (<code>' '</code>).</p>
  3602. *
  3603. * <p><code>null</code> will return <code>false</code>.
  3604. * An empty String ("") will return <code>true</code>.</p>
  3605. *
  3606. * <pre>
  3607. * StringUtils.isAlphanumeric(null) = false
  3608. * StringUtils.isAlphanumeric("") = true
  3609. * StringUtils.isAlphanumeric(" ") = true
  3610. * StringUtils.isAlphanumeric("abc") = true
  3611. * StringUtils.isAlphanumeric("ab c") = true
  3612. * StringUtils.isAlphanumeric("ab2c") = true
  3613. * StringUtils.isAlphanumeric("ab-c") = false
  3614. * </pre>
  3615. *
  3616. * @param str the String to check, may be null
  3617. * @return <code>true</code> if only contains letters, digits or space,
  3618. * and is non-null
  3619. */
  3620. public static boolean isAlphanumericSpace(String str) {
  3621. if (str == null) {
  3622. return false;
  3623. }
  3624. int sz = str.length();
  3625. for (int i = 0; i < sz; i++) {
  3626. if ((Character.isLetterOrDigit(str.charAt(i)) == false) &&
  3627. (str.charAt(i) != ' ')) {
  3628. return false;
  3629. }
  3630. }
  3631. return true;
  3632. }
  3633. /**
  3634. * <p>Checks if the String contains only unicode digits.
  3635. * A decimal point is not a unicode digit and returns false.</p>
  3636. *
  3637. * <p><code>null</code> will return <code>false</code>.
  3638. * An empty String ("") will return <code>true</code>.</p>
  3639. *
  3640. * <pre>
  3641. * StringUtils.isNumeric(null) = false
  3642. * StringUtils.isNumeric("") = true
  3643. * StringUtils.isNumeric(" ") = false
  3644. * StringUtils.isNumeric("123") = true
  3645. * StringUtils.isNumeric("12 3") = false
  3646. * StringUtils.isNumeric("ab2c") = false
  3647. * StringUtils.isNumeric("12-3") = false
  3648. * StringUtils.isNumeric("12.3") = false
  3649. * </pre>
  3650. *
  3651. * @param str the String to check, may be null
  3652. * @return <code>true</code> if only contains digits, and is non-null
  3653. */
  3654. public static boolean isNumeric(String str) {
  3655. if (str == null) {
  3656. return false;
  3657. }
  3658. int sz = str.length();
  3659. for (int i = 0; i < sz; i++) {
  3660. if (Character.isDigit(str.charAt(i)) == false) {
  3661. return false;
  3662. }
  3663. }
  3664. return true;
  3665. }
  3666. /**
  3667. * <p>Checks if the String contains only unicode digits or space
  3668. * (<code>' '</code>).
  3669. * A decimal point is not a unicode digit and returns false.</p>
  3670. *
  3671. * <p><code>null</code> will return <code>false</code>.
  3672. * An empty String ("") will return <code>true</code>.</p>
  3673. *
  3674. * <pre>
  3675. * StringUtils.isNumeric(null) = false
  3676. * StringUtils.isNumeric("") = true
  3677. * StringUtils.isNumeric(" ") = true
  3678. * StringUtils.isNumeric("123") = true
  3679. * StringUtils.isNumeric("12 3") = true
  3680. * StringUtils.isNumeric("ab2c") = false
  3681. * StringUtils.isNumeric("12-3") = false
  3682. * StringUtils.isNumeric("12.3") = false
  3683. * </pre>
  3684. *
  3685. * @param str the String to check, may be null
  3686. * @return <code>true</code> if only contains digits or space,
  3687. * and is non-null
  3688. */
  3689. public static boolean isNumericSpace(String str) {
  3690. if (str == null) {
  3691. return false;
  3692. }
  3693. int sz = str.length();
  3694. for (int i = 0; i < sz; i++) {
  3695. if ((Character.isDigit(str.charAt(i)) == false) &&
  3696. (str.charAt(i) != ' ')) {
  3697. return false;
  3698. }
  3699. }
  3700. return true;
  3701. }
  3702. /**
  3703. * <p>Checks if the String contains only whitespace.</p>
  3704. *
  3705. * <p><code>null</code> will return <code>false</code>.
  3706. * An empty String ("") will return <code>true</code>.</p>
  3707. *
  3708. * <pre>
  3709. * StringUtils.isWhitespace(null) = false
  3710. * StringUtils.isWhitespace("") = true
  3711. * StringUtils.isWhitespace(" ") = true
  3712. * StringUtils.isWhitespace("abc") = false
  3713. * StringUtils.isWhitespace("ab2c") = false
  3714. * StringUtils.isWhitespace("ab-c") = false
  3715. * </pre>
  3716. *
  3717. * @param str the String to check, may be null
  3718. * @return <code>true</code> if only contains whitespace, and is non-null
  3719. * @since 2.0
  3720. */
  3721. public static boolean isWhitespace(String str) {
  3722. if (str == null) {
  3723. return false;
  3724. }
  3725. int sz = str.length();
  3726. for (int i = 0; i < sz; i++) {
  3727. if ((Character.isWhitespace(str.charAt(i)) == false) ) {
  3728. return false;
  3729. }
  3730. }
  3731. return true;
  3732. }
  3733. // Defaults
  3734. //-----------------------------------------------------------------------
  3735. /**
  3736. * <p>Returns either the passed in String,
  3737. * or if the String is <code>null</code>, an empty String ("").</p>
  3738. *
  3739. * <pre>
  3740. * StringUtils.defaultString(null) = ""
  3741. * StringUtils.defaultString("") = ""
  3742. * StringUtils.defaultString("bat") = "bat"
  3743. * </pre>
  3744. *
  3745. * @see ObjectUtils#toString(Object)
  3746. * @see String#valueOf(Object)
  3747. * @param str the String to check, may be null
  3748. * @return the passed in String, or the empty String if it
  3749. * was <code>null</code>
  3750. */
  3751. public static String defaultString(String str) {
  3752. return (str == null ? EMPTY : str);
  3753. }
  3754. /**
  3755. * <p>Returns either the passed in String,
  3756. * or if the String is <code>null</code>, an empty String ("").</p>
  3757. *
  3758. * <pre>
  3759. * StringUtils.defaultString(null, "null") = "null"
  3760. * StringUtils.defaultString("", "null") = ""
  3761. * StringUtils.defaultString("bat", "null") = "bat"
  3762. * </pre>
  3763. *
  3764. * @see ObjectUtils#toString(Object,String)
  3765. * @see String#valueOf(Object)
  3766. * @param str the String to check, may be null
  3767. * @param defaultStr the default String to return
  3768. * if the input is <code>null</code>, may be null
  3769. * @return the passed in String, or the default if it was <code>null</code>
  3770. */
  3771. public static String defaultString(String str, String defaultStr) {
  3772. return (str == null ? defaultStr : str);
  3773. }
  3774. // Reversing
  3775. //-----------------------------------------------------------------------
  3776. /**
  3777. * <p>Reverses a String as per {@link StringBuffer#reverse()}.</p>
  3778. *
  3779. * <p><A code>null</code> String returns <code>null</code>.</p>
  3780. *
  3781. * <pre>
  3782. * StringUtils.reverse(null) = null
  3783. * StringUtils.reverse("") = ""
  3784. * StringUtils.reverse("bat") = "tab"
  3785. * </pre>
  3786. *
  3787. * @param str the String to reverse, may be null
  3788. * @return the reversed String, <code>null</code> if null String input
  3789. */
  3790. public static String reverse(String str) {
  3791. if (str == null) {
  3792. return null;
  3793. }
  3794. return new StringBuffer(str).reverse().toString();
  3795. }
  3796. /**
  3797. * <p>Reverses a String that is delimited by a specific character.</p>
  3798. *
  3799. * <p>The Strings between the delimiters are not reversed.
  3800. * Thus java.lang.String becomes String.lang.java (if the delimiter
  3801. * is <code>'.'</code>).</p>
  3802. *
  3803. * <pre>
  3804. * StringUtils.reverseDelimited(null, *) = null
  3805. * StringUtils.reverseDelimited("", *) = ""
  3806. * StringUtils.reverseDelimited("a.b.c", 'x') = "a.b.c"
  3807. * StringUtils.reverseDelimited("a.b.c", ".") = "c.b.a"
  3808. * </pre>
  3809. *
  3810. * @param str the String to reverse, may be null
  3811. * @param separatorChar the separator character to use
  3812. * @return the reversed String, <code>null</code> if null String input
  3813. * @since 2.0
  3814. */
  3815. public static String reverseDelimited(String str, char separatorChar) {
  3816. if (str == null) {
  3817. return null;
  3818. }
  3819. // could implement manually, but simple way is to reuse other,
  3820. // probably slower, methods.
  3821. String[] strs = split(str, separatorChar);
  3822. ArrayUtils.reverse(strs);
  3823. return join(strs, separatorChar);
  3824. }
  3825. /**
  3826. * <p>Reverses a String that is delimited by a specific character.</p>
  3827. *
  3828. * <p>The Strings between the delimiters are not reversed.
  3829. * Thus java.lang.String becomes String.lang.java (if the delimiter
  3830. * is <code>"."</code>).</p>
  3831. *
  3832. * <pre>
  3833. * StringUtils.reverseDelimitedString(null, *) = null
  3834. * StringUtils.reverseDelimitedString("",*) = ""
  3835. * StringUtils.reverseDelimitedString("a.b.c", null) = "a.b.c"
  3836. * StringUtils.reverseDelimitedString("a.b.c", ".") = "c.b.a"
  3837. * </pre>
  3838. *
  3839. * @param str the String to reverse, may be null
  3840. * @param separatorChars the separator characters to use, null treated as whitespace
  3841. * @return the reversed String, <code>null</code> if null String input
  3842. * @deprecated Use {@link #reverseDelimited(String, char)} instead.
  3843. * This method is broken as the join doesn't know which char to use.
  3844. * Method will be removed in Commons Lang 3.0.
  3845. *
  3846. */
  3847. public static String reverseDelimitedString(String str, String separatorChars) {
  3848. if (str == null) {
  3849. return null;
  3850. }
  3851. // could implement manually, but simple way is to reuse other,
  3852. // probably slower, methods.
  3853. String[] strs = split(str, separatorChars);
  3854. ArrayUtils.reverse(strs);
  3855. if (separatorChars == null) {
  3856. return join(strs, ' ');
  3857. }
  3858. return join(strs, separatorChars);
  3859. }
  3860. // Abbreviating
  3861. //-----------------------------------------------------------------------
  3862. /**
  3863. * <p>Abbreviates a String using ellipses. This will turn
  3864. * "Now is the time for all good men" into "Now is the time for..."</p>
  3865. *
  3866. * <p>Specifically:
  3867. * <ul>
  3868. * <li>If <code>str</code> is less than <code>maxWidth</code> characters
  3869. * long, return it.</li>
  3870. * <li>Else abbreviate it to <code>(substring(str, 0, max-3) + "...")</code>.</li>
  3871. * <li>If <code>maxWidth</code> is less than <code>4</code>, throw an
  3872. * <code>IllegalArgumentException</code>.</li>
  3873. * <li>In no case will it return a String of length greater than
  3874. * <code>maxWidth</code>.</li>
  3875. * </ul>
  3876. * </p>
  3877. *
  3878. * <pre>
  3879. * StringUtils.abbreviate(null, *) = null
  3880. * StringUtils.abbreviate("", 4) = ""
  3881. * StringUtils.abbreviate("abcdefg", 6) = "abc..."
  3882. * StringUtils.abbreviate("abcdefg", 7) = "abcdefg"
  3883. * StringUtils.abbreviate("abcdefg", 8) = "abcdefg"
  3884. * StringUtils.abbreviate("abcdefg", 4) = "a..."
  3885. * StringUtils.abbreviate("abcdefg", 3) = IllegalArgumentException
  3886. * </pre>
  3887. *
  3888. * @param str the String to check, may be null
  3889. * @param maxWidth maximum length of result String, must be at least 4
  3890. * @return abbreviated String, <code>null</code> if null String input
  3891. * @throws IllegalArgumentException if the width is too small
  3892. * @since 2.0
  3893. */
  3894. public static String abbreviate(String str, int maxWidth) {
  3895. return abbreviate(str, 0, maxWidth);
  3896. }
  3897. /**
  3898. * <p>Abbreviates a String using ellipses. This will turn
  3899. * "Now is the time for all good men" into "...is the time for..."</p>
  3900. *
  3901. * <p>Works like <code>abbreviate(String, int)</code>, but allows you to specify
  3902. * a "left edge" offset. Note that this left edge is not necessarily going to
  3903. * be the leftmost character in the result, or the first character following the
  3904. * ellipses, but it will appear somewhere in the result.
  3905. *
  3906. * <p>In no case will it return a String of length greater than
  3907. * <code>maxWidth</code>.</p>
  3908. *
  3909. * <pre>
  3910. * StringUtils.abbreviate(null, *, *) = null
  3911. * StringUtils.abbreviate("", 0, 4) = ""
  3912. * StringUtils.abbreviate("abcdefghijklmno", -1, 10) = "abcdefg..."
  3913. * StringUtils.abbreviate("abcdefghijklmno", 0, 10) = "abcdefg..."
  3914. * StringUtils.abbreviate("abcdefghijklmno", 1, 10) = "abcdefg..."
  3915. * StringUtils.abbreviate("abcdefghijklmno", 4, 10) = "abcdefg..."
  3916. * StringUtils.abbreviate("abcdefghijklmno", 5, 10) = "...fghi..."
  3917. * StringUtils.abbreviate("abcdefghijklmno", 6, 10) = "...ghij..."
  3918. * StringUtils.abbreviate("abcdefghijklmno", 8, 10) = "...ijklmno"
  3919. * StringUtils.abbreviate("abcdefghijklmno", 10, 10) = "...ijklmno"
  3920. * StringUtils.abbreviate("abcdefghijklmno", 12, 10) = "...ijklmno"
  3921. * StringUtils.abbreviate("abcdefghij", 0, 3) = IllegalArgumentException
  3922. * StringUtils.abbreviate("abcdefghij", 5, 6) = IllegalArgumentException
  3923. * </pre>
  3924. *
  3925. * @param str the String to check, may be null
  3926. * @param offset left edge of source String
  3927. * @param maxWidth maximum length of result String, must be at least 4
  3928. * @return abbreviated String, <code>null</code> if null String input
  3929. * @throws IllegalArgumentException if the width is too small
  3930. * @since 2.0
  3931. */
  3932. public static String abbreviate(String str, int offset, int maxWidth) {
  3933. if (str == null) {
  3934. return null;
  3935. }
  3936. if (maxWidth < 4) {
  3937. throw new IllegalArgumentException("Minimum abbreviation width is 4");
  3938. }
  3939. if (str.length() <= maxWidth) {
  3940. return str;
  3941. }
  3942. if (offset > str.length()) {
  3943. offset = str.length();
  3944. }
  3945. if ((str.length() - offset) < (maxWidth - 3)) {
  3946. offset = str.length() - (maxWidth - 3);
  3947. }
  3948. if (offset <= 4) {
  3949. return str.substring(0, maxWidth - 3) + "...";
  3950. }
  3951. if (maxWidth < 7) {
  3952. throw new IllegalArgumentException("Minimum abbreviation width with offset is 7");
  3953. }
  3954. if ((offset + (maxWidth - 3)) < str.length()) {
  3955. return "..." + abbreviate(str.substring(offset), maxWidth - 3);
  3956. }
  3957. return "..." + str.substring(str.length() - (maxWidth - 3));
  3958. }
  3959. // Difference
  3960. //-----------------------------------------------------------------------
  3961. /**
  3962. * <p>Compares two Strings, and returns the portion where they differ.
  3963. * (More precisely, return the remainder of the second String,
  3964. * starting from where it's different from the first.)</p>
  3965. *
  3966. * <p>For example,
  3967. * <code>difference("i am a machine", "i am a robot") -> "robot"</code>.</p>
  3968. *
  3969. * <pre>
  3970. * StringUtils.difference(null, null) = null
  3971. * StringUtils.difference("", "") = ""
  3972. * StringUtils.difference("", "abc") = "abc"
  3973. * StringUtils.difference("abc", "") = ""
  3974. * StringUtils.difference("abc", "abc") = ""
  3975. * StringUtils.difference("ab", "abxyz") = "xyz"
  3976. * StringUtils.difference("abcde", "abxyz") = "xyz"
  3977. * StringUtils.difference("abcde", "xyz") = "xyz"
  3978. * </pre>
  3979. *
  3980. * @param str1 the first String, may be null
  3981. * @param str2 the second String, may be null
  3982. * @return the portion of str2 where it differs from str1; returns the
  3983. * empty String if they are equal
  3984. * @since 2.0
  3985. */
  3986. public static String difference(String str1, String str2) {
  3987. if (str1 == null) {
  3988. return str2;
  3989. }
  3990. if (str2 == null) {
  3991. return str1;
  3992. }
  3993. int at = indexOfDifference(str1, str2);
  3994. if (at == -1) {
  3995. return EMPTY;
  3996. }
  3997. return str2.substring(at);
  3998. }
  3999. /**
  4000. * <p>Compares two Strings, and returns the index at which the
  4001. * Strings begin to differ.</p>
  4002. *
  4003. * <p>For example,
  4004. * <code>indexOfDifference("i am a machine", "i am a robot") -> 7</code></p>
  4005. *
  4006. * <pre>
  4007. * StringUtils.indexOfDifference(null, null) = -1
  4008. * StringUtils.indexOfDifference("", "") = -1
  4009. * StringUtils.indexOfDifference("", "abc") = 0
  4010. * StringUtils.indexOfDifference("abc", "") = 0
  4011. * StringUtils.indexOfDifference("abc", "abc") = -1
  4012. * StringUtils.indexOfDifference("ab", "abxyz") = 2
  4013. * StringUtils.indexOfDifference("abcde", "abxyz") = 2
  4014. * StringUtils.indexOfDifference("abcde", "xyz") = 0
  4015. * </pre>
  4016. *
  4017. * @param str1 the first String, may be null
  4018. * @param str2 the second String, may be null
  4019. * @return the index where str2 and str1 begin to differ; -1 if they are equal
  4020. * @since 2.0
  4021. */
  4022. public static int indexOfDifference(String str1, String str2) {
  4023. if (str1 == str2) {
  4024. return -1;
  4025. }
  4026. if (str1 == null || str2 == null) {
  4027. return 0;
  4028. }
  4029. int i;
  4030. for (i = 0; i < str1.length() && i < str2.length(); ++i) {
  4031. if (str1.charAt(i) != str2.charAt(i)) {
  4032. break;
  4033. }
  4034. }
  4035. if (i < str2.length() || i < str1.length()) {
  4036. return i;
  4037. }
  4038. return -1;
  4039. }
  4040. // Misc
  4041. //-----------------------------------------------------------------------
  4042. /**
  4043. * <p>Find the Levenshtein distance between two Strings.</p>
  4044. *
  4045. * <p>This is the number of changes needed to change one String into
  4046. * another, where each change is a single character modification (deletion,
  4047. * insertion or substitution).</p>
  4048. *
  4049. * <p>This implementation of the Levenshtein distance algorithm
  4050. * is from <a href="http://www.merriampark.com/ld.htm">http://www.merriampark.com/ld.htm</a></p>
  4051. *
  4052. * <pre>
  4053. * StringUtils.getLevenshteinDistance(null, *) = IllegalArgumentException
  4054. * StringUtils.getLevenshteinDistance(*, null) = IllegalArgumentException
  4055. * StringUtils.getLevenshteinDistance("","") = 0
  4056. * StringUtils.getLevenshteinDistance("","a") = 1
  4057. * StringUtils.getLevenshteinDistance("aaapppp", "") = 7
  4058. * StringUtils.getLevenshteinDistance("frog", "fog") = 1
  4059. * StringUtils.getLevenshteinDistance("fly", "ant") = 3
  4060. * StringUtils.getLevenshteinDistance("elephant", "hippo") = 7
  4061. * StringUtils.getLevenshteinDistance("hippo", "elephant") = 7
  4062. * StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz") = 8
  4063. * StringUtils.getLevenshteinDistance("hello", "hallo") = 1
  4064. * </pre>
  4065. *
  4066. * @param s the first String, must not be null
  4067. * @param t the second String, must not be null
  4068. * @return result distance
  4069. * @throws IllegalArgumentException if either String input <code>null</code>
  4070. */
  4071. public static int getLevenshteinDistance(String s, String t) {
  4072. if (s == null || t == null) {
  4073. throw new IllegalArgumentException("Strings must not be null");
  4074. }
  4075. int d[][]; // matrix
  4076. int n; // length of s
  4077. int m; // length of t
  4078. int i; // iterates through s
  4079. int j; // iterates through t
  4080. char s_i; // ith character of s
  4081. char t_j; // jth character of t
  4082. int cost; // cost
  4083. // Step 1
  4084. n = s.length();
  4085. m = t.length();
  4086. if (n == 0) {
  4087. return m;
  4088. }
  4089. if (m == 0) {
  4090. return n;
  4091. }
  4092. d = new int[n + 1][m + 1];
  4093. // Step 2
  4094. for (i = 0; i <= n; i++) {
  4095. d[i][0] = i;
  4096. }
  4097. for (j = 0; j <= m; j++) {
  4098. d[0][j] = j;
  4099. }
  4100. // Step 3
  4101. for (i = 1; i <= n; i++) {
  4102. s_i = s.charAt(i - 1);
  4103. // Step 4
  4104. for (j = 1; j <= m; j++) {
  4105. t_j = t.charAt(j - 1);
  4106. // Step 5
  4107. if (s_i == t_j) {
  4108. cost = 0;
  4109. } else {
  4110. cost = 1;
  4111. }
  4112. // Step 6
  4113. d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
  4114. }
  4115. }
  4116. // Step 7
  4117. return d[n][m];
  4118. }
  4119. /**
  4120. * <p>Gets the minimum of three <code>int</code> values.</p>
  4121. *
  4122. * @param a value 1
  4123. * @param b value 2
  4124. * @param c value 3
  4125. * @return the smallest of the values
  4126. */
  4127. private static int min(int a, int b, int c) {
  4128. // Method copied from NumberUtils to avoid dependency on subpackage
  4129. if (b < a) {
  4130. a = b;
  4131. }
  4132. if (c < a) {
  4133. a = c;
  4134. }
  4135. return a;
  4136. }
  4137. }