Skip to content

Commit

Permalink
Added StringUtilities.count(content, token) which returns the number …
Browse files Browse the repository at this point in the history
…of times the token is inside the content.
  • Loading branch information
jdereg committed Oct 30, 2023
1 parent 8fbb5e2 commit 78ff1de
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 8 deletions.
38 changes: 30 additions & 8 deletions src/main/java/com/cedarsoftware/util/StringUtilities.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand Down
11 changes: 11 additions & 0 deletions src/test/java/com/cedarsoftware/util/TestStringUtilities.java
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
}

0 comments on commit 78ff1de

Please sign in to comment.