Added support for format method. Still need to add support for named parameters.

This commit is contained in:
Shekhar Gulati
2016-05-17 20:10:15 +05:30
parent 176525cc0e
commit b42ff8338e
2 changed files with 39 additions and 0 deletions
+24
View File
@@ -6,6 +6,8 @@ import java.util.Optional;
import java.util.StringJoiner;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import static java.util.stream.Collectors.joining;
@@ -416,6 +418,28 @@ public abstract class Strman {
return first(value, 1);
}
/**
* Formats a string using parameters
*
* @param value The value to be formatted
* @param params Parameters to be described in the string
* @return The formatted string
*/
public static String format(final String value, String... params) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
Pattern p = Pattern.compile("\\{(\\w+)\\}");
Matcher m = p.matcher(value);
String result = value;
while (m.find()) {
int paramNumber = Integer.parseInt(m.group(1));
if (params == null || paramNumber >= params.length) {
throw new IllegalArgumentException("params does not have value for " + m.group());
}
result = result.replace(m.group(), params[paramNumber]);
}
return result;
}
public static String leftPad(final String value, final String pad, final int length) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
if (value.length() >= length) {
+15
View File
@@ -11,6 +11,7 @@ import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.collection.IsArrayContainingInOrder.arrayContaining;
import static org.junit.Assert.*;
import static strman.Strman.*;
import static strman.Strman.format;
public class StrmanTest {
@@ -327,4 +328,18 @@ public class StrmanTest {
Arrays.stream(fixture).forEach(el -> assertThat(head(el), equalTo("f")));
}
@Test
public void format_shouldFormatStringsToFooBar() throws Exception {
assertThat(format("{0} bar", "foo"), equalTo("foo bar"));
assertThat(format("foo {0}", "bar"), equalTo("foo bar"));
assertThat(format("foo {0}", "bar", "foo"), equalTo("foo bar"));
assertThat(format("{0} {1}", "foo", "bar"), equalTo("foo bar"));
assertThat(format("{1} {0}", "bar", "foo"), equalTo("foo bar"));
}
@Test(expected = IllegalArgumentException.class)
public void format_shouldThrowExceptionWhenValueDoesNotExist() throws Exception {
assertThat(format("{1} {0}"), equalTo("{1} {0}"));
}
}