From f6346b87a413c9e45fcfa7d059e60bb270ba4584 Mon Sep 17 00:00:00 2001 From: Javen O'Neal Date: Wed, 19 Oct 2016 23:04:16 +0000 Subject: [PATCH] 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 --- src/java/org/apache/poi/util/StringUtil.java | 20 +++++++++++++++++++ .../org/apache/poi/util/TestStringUtil.java | 19 ++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/src/java/org/apache/poi/util/StringUtil.java b/src/java/org/apache/poi/util/StringUtil.java index 6272c14e50..2b8c81fdd1 100644 --- a/src/java/org/apache/poi/util/StringUtil.java +++ b/src/java/org/apache/poi/util/StringUtil.java @@ -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