Add new pluralFormat method...

This commit is contained in:
2023-02-27 11:01:29 -06:00
parent 4f3c03de1a
commit d41e92d213
2 changed files with 55 additions and 0 deletions

View File

@ -313,6 +313,42 @@ public class StringUtils
/*******************************************************************************
** Given a "formatString" containing any number of {singular,plural} style "tokens",
** replace the "tokens" with the "singular" options if the 'size' parameter is 1
** or the "plural" options if not-1 (e.g., 0 or 2+)
**
** e.g.: StringUtils.pluralFormat(n, "Apple{,s} {was,were} eaten")) // seems easier.
** e.g.: StringUtils.pluralFormat(n, "Apple{ was,s were} eaten")) // also works...
*******************************************************************************/
public static String pluralFormat(Integer size, String formatString)
{
int lastIndex = 0;
StringBuilder output = new StringBuilder();
Pattern pattern = Pattern.compile("\\{.*?,.*?}");
Matcher matcher = pattern.matcher(formatString);
while(matcher.find())
{
String group = matcher.group();
String groupBody = group.substring(1, group.length() - 1);
String[] groupParts = groupBody.split(",", 2);
String replacement = (size == 1) ? groupParts[0] : groupParts[1];
output.append(formatString, lastIndex, matcher.start()).append(replacement);
lastIndex = matcher.end();
}
if(lastIndex < formatString.length())
{
output.append(formatString, lastIndex, formatString.length());
}
return (output.toString());
}
/******************************************************************************* /*******************************************************************************
** Switch between strings based on if the size of the parameter collection. If ** Switch between strings based on if the size of the parameter collection. If
** it is 1 (the singular) or not-1 (0 or 2+, the plural). Get back "" or "s" ** it is 1 (the singular) or not-1 (0 or 2+, the plural). Get back "" or "s"

View File

@ -285,4 +285,23 @@ class StringUtilsTest extends BaseTest
assertEquals("Abc", StringUtils.ucFirst("abc")); assertEquals("Abc", StringUtils.ucFirst("abc"));
} }
/*******************************************************************************
**
*******************************************************************************/
@Test
void testPluralFormat()
{
assertEquals("Apple", StringUtils.pluralFormat(1, "Apple{,s}"));
assertEquals("Apples", StringUtils.pluralFormat(0, "Apple{,s}"));
assertEquals("Apples", StringUtils.pluralFormat(2, "Apple{,s}"));
assertEquals("Apple and Orange", StringUtils.pluralFormat(1, "Apple{,s} and Orange{,s}"));
assertEquals("Apples and Oranges", StringUtils.pluralFormat(2, "Apple{,s} and Orange{,s}"));
assertEquals("Apple was eaten", StringUtils.pluralFormat(1, "Apple{,s} {was,were} eaten"));
assertEquals("Apples were eaten", StringUtils.pluralFormat(2, "Apple{,s} {was,were} eaten"));
}
} }