From 78ff1decc675472bfa3dabc7818de5ec9a486899 Mon Sep 17 00:00:00 2001 From: John DeRegnaucourt Date: Sun, 29 Oct 2023 23:24:43 -0400 Subject: [PATCH] Added StringUtilities.count(content, token) which returns the number of times the token is inside the content. --- .../cedarsoftware/util/StringUtilities.java | 38 +++++++++++++++---- .../util/TestStringUtilities.java | 11 ++++++ 2 files changed, 41 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/cedarsoftware/util/StringUtilities.java b/src/main/java/com/cedarsoftware/util/StringUtilities.java index b287ee89..51a2f5b8 100644 --- a/src/main/java/com/cedarsoftware/util/StringUtilities.java +++ b/src/main/java/com/cedarsoftware/util/StringUtilities.java @@ -169,22 +169,44 @@ private static char convertDigit(int value) public static int count(String s, char c) { - if (isEmpty(s)) + return count (s, "" + c); + } + + /** + * Count the number of times that 'token' occurs within 'content'. + * @return int count (0 if it never occurs, null is the source string, or null is the token). + */ + public static int count(CharSequence content, CharSequence token) + { + if (content == null || token == null) { return 0; } - final int len = s.length(); - int count = 0; - for (int i = 0; i < len; i++) + String source = content.toString(); + if (source.isEmpty()) + { + return 0; + } + String sub = token.toString(); + if (sub.isEmpty()) + { + return 0; + } + + int answer = 0; + int idx = 0; + + while (true) { - if (s.charAt(i) == c) + idx = source.indexOf(sub, idx); + if (idx < answer) { - count++; + return answer; } + answer = ++answer; + idx = ++idx; } - - return count; } /** diff --git a/src/test/java/com/cedarsoftware/util/TestStringUtilities.java b/src/test/java/com/cedarsoftware/util/TestStringUtilities.java index 0184a60b..7c32c1c1 100644 --- a/src/test/java/com/cedarsoftware/util/TestStringUtilities.java +++ b/src/test/java/com/cedarsoftware/util/TestStringUtilities.java @@ -376,4 +376,15 @@ public void testHashCodeIgnoreCase() assert StringUtilities.hashCodeIgnoreCase(null) == 0; assert StringUtilities.hashCodeIgnoreCase("") == 0; } + + @Test + public void testCount2() + { + assert 0 == StringUtilities.count("alphabet", null); + assert 0 == StringUtilities.count(null, "al"); + assert 0 == StringUtilities.count("alphabet", ""); + assert 0 == StringUtilities.count("", "al"); + assert 1 == StringUtilities.count("alphabet", "al"); + assert 2 == StringUtilities.count("halal", "al"); + } }