add StringUtil.count, inspired by Apache Commons Lang StringUtils#countMatches and Python's str.count(substr)
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1765730 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
parent
4b01accdb3
commit
5d3d50b9d1
@ -590,4 +590,24 @@ public class StringUtil {
|
||||
public static String join(String separator, Object... array) {
|
||||
return join(array, separator);
|
||||
}
|
||||
|
||||
/**
|
||||
* Count number of occurrences of needle in haystack
|
||||
* Has same signature as org.apache.commons.lang3.StringUtils#countMatches
|
||||
*
|
||||
* @param haystack the CharSequence to check, may be null
|
||||
* @param needle the character to count the quantity of
|
||||
* @return the number of occurrences, 0 if the CharSequence is null
|
||||
*/
|
||||
public static int countMatches(CharSequence haystack, char needle) {
|
||||
if (haystack == null) return 0;
|
||||
int count = 0;
|
||||
final int length = haystack.length();
|
||||
for (int i=0; i<length; i++) {
|
||||
if (haystack.charAt(i) == needle) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
}
|
||||
|
@ -192,5 +192,24 @@ public class TestStringUtil {
|
||||
assertEquals("abc|def|ghi", StringUtil.join("|", "abc", "def", "ghi"));
|
||||
assertEquals("5|8.5|true|string", StringUtil.join("|", 5, 8.5, true, "string")); //assumes Locale prints number decimal point as a period rather than a comma
|
||||
}
|
||||
|
||||
@Test
|
||||
public void count() {
|
||||
String test = "Apache POI project\n\u00a9 Copyright 2016";
|
||||
// supports search in null or empty string
|
||||
assertEquals("null", 0, StringUtil.countMatches(null, 'A'));
|
||||
assertEquals("empty string", 0, StringUtil.countMatches("", 'A'));
|
||||
|
||||
assertEquals("normal", 2, StringUtil.countMatches(test, 'e'));
|
||||
assertEquals("normal, should not find a in escaped copyright", 1, StringUtil.countMatches(test, 'a'));
|
||||
|
||||
// search for non-printable characters
|
||||
assertEquals("null character", 0, StringUtil.countMatches(test, '\0'));
|
||||
assertEquals("CR", 0, StringUtil.countMatches(test, '\r'));
|
||||
assertEquals("LF", 1, StringUtil.countMatches(test, '\n'));
|
||||
|
||||
// search for unicode characters
|
||||
assertEquals("Unicode", 1, StringUtil.countMatches(test, '\u00a9'));
|
||||
}
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user