LANG-1307: Added getDigits method to StringUtils (closes #225)

This commit is contained in:
Arshad Basha 2017-01-03 00:14:33 +05:30 committed by pascalschumacher
parent c8e648b92c
commit 9b3257e4d1
2 changed files with 47 additions and 0 deletions

View File

@ -7156,6 +7156,42 @@ public static boolean isNumericSpace(final CharSequence cs) {
return true;
}
/**
* <p>Checks if a String {@code str} contains Unicode digits,
* if yes then concatenate all the digits in {@code str} and return it as a String.</p>
*
* <p>An empty ("") String will be returned if no digits found in {@code str}.</p>
*
* <pre>
* StringUtils.getDigits(null) = null
* StringUtils.getDigits("") = ""
* StringUtils.getDigits("abc") = ""
* StringUtils.getDigits("1000$") = "1000"
* StringUtils.getDigits("1123~45") = "12345"
* StringUtils.getDigits("(541) 754-3010") = "5417543010"
* StringUtils.getDigits("\u0967\u0968\u0969") = "\u0967\u0968\u0969"
* </pre>
*
* @param str the String to extract digits from, may be null
* @return String with only digits,
* or an empty ("") String if no digits found,
* or {@code null} String if {@code str} is null
*/
public static String getDigits(final String str) {
if (isEmpty(str)) {
return str;
}
final int sz = str.length();
final StringBuilder strDigits = new StringBuilder(sz);
for (int i = 0; i < sz; i++) {
final char tempChar = str.charAt(i);
if (Character.isDigit(tempChar)) {
strDigits.append(tempChar);
}
}
return strDigits.toString();
}
/**
* <p>Checks if the CharSequence contains only whitespace.</p>
*

View File

@ -3206,4 +3206,15 @@ public void testToCodePoints() throws Exception {
assertNull(StringUtils.toCodePoints(null));
assertArrayEquals(ArrayUtils.EMPTY_INT_ARRAY, StringUtils.toCodePoints(""));
}
@Test
public void testGetDigits() {
assertEquals(null, StringUtils.getDigits(null));
assertEquals("", StringUtils.getDigits(""));
assertEquals("", StringUtils.getDigits("abc"));
assertEquals("1000", StringUtils.getDigits("1000$"));
assertEquals("12345", StringUtils.getDigits("123password45"));
assertEquals("5417543010", StringUtils.getDigits("(541) 754-3010"));
assertEquals("\u0967\u0968\u0969", StringUtils.getDigits("\u0967\u0968\u0969"));
}
}