16 Commits
4 changed files with 406 additions and 25 deletions
+2 -5
View File
@@ -15,8 +15,7 @@ For Apache Maven users, please add following to your pom.xml.
<dependency>
<groupId>com.shekhargulati</groupId>
<artifactId>strman</artifactId>
<version>0.1.0</version>
<type>jar</type>
<version>0.2.0</version>
</dependency>
</dependencies>
```
@@ -24,9 +23,7 @@ For Apache Maven users, please add following to your pom.xml.
Gradle users can add following to their build.gradle file.
```
compile(group: 'com.shekhargulati', name: 'strman', version: '0.1.0', ext: 'jar'){
transitive=true
}
compile(group: 'com.shekhargulati', name: 'strman', version: '0.2.0')
```
## Available Functions
+1 -1
View File
@@ -1 +1 @@
version=0.2.0
version=0.3.0
+213 -11
View File
@@ -34,6 +34,9 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.joining;
/**
@@ -87,7 +90,7 @@ public abstract class Strman {
* @return an Optional String if found else empty
*/
public static Optional<String> at(final String value, int index) {
if (value == null || value.isEmpty()) {
if (isNullOrEmpty(value)) {
return Optional.empty();
}
int length = value.length();
@@ -97,6 +100,10 @@ public abstract class Strman {
return (index < length && index >= 0) ? Optional.of(String.valueOf(value.charAt(index))) : Optional.empty();
}
private static boolean isNullOrEmpty(String input) {
return input == null || input.isEmpty();
}
/**
* Returns an array with strings between start and end.
*
@@ -175,7 +182,7 @@ public abstract class Strman {
*/
public static boolean containsAll(final String value, final String[] needles) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return Arrays.stream(needles).allMatch(needle -> contains(value, needle, true));
return Arrays.stream(needles).allMatch(needle -> contains(value, needle, false));
}
/**
@@ -405,9 +412,8 @@ public abstract class Strman {
* @param n Number of chars to return
* @return The first n chars
*/
public static String first(final String value, final int n) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return value.substring(0, n);
public static Optional<String> first(final String value, final int n) {
return Optional.ofNullable(value).filter(v -> !v.isEmpty()).map(v -> v.substring(0, n));
}
/**
@@ -416,7 +422,7 @@ public abstract class Strman {
* @param value The input String
* @return The first char
*/
public static String head(final String value) {
public static Optional<String> head(final String value) {
return first(value, 1);
}
@@ -944,7 +950,11 @@ public abstract class Strman {
*/
public static String htmlEncode(final String html) {
validate(html, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return html.chars().mapToObj(c -> "\\u" + String.format("%04x", c).toUpperCase()).map(e -> HtmlEntities.encodedEntities.get(e)).collect(joining());
return html
.chars()
.mapToObj(c -> "\\u" + String.format("%04x", c).toUpperCase())
.map(HtmlEntities.encodedEntities::get)
.collect(joining());
}
/**
@@ -1045,7 +1055,10 @@ public abstract class Strman {
public static String toStudlyCase(final String value) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
String[] words = collapseWhitespace(value.trim()).split("\\s*(_|-|\\s)\\s*");
return Arrays.stream(words).filter(w -> !w.trim().isEmpty()).map(w -> head(w).toUpperCase() + tail(w)).collect(joining());
return Arrays.stream(words)
.filter(w -> !w.trim().isEmpty())
.map(Strman::upperFirst)
.collect(joining());
}
/**
@@ -1054,9 +1067,8 @@ public abstract class Strman {
* @param value The input String
* @return String tail
*/
public static String tail(final String value) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return last(value, value.length() - 1);
public static Optional<String> tail(final String value) {
return Optional.ofNullable(value).filter(v -> !v.isEmpty()).map(v -> last(v, v.length() - 1));
}
/**
@@ -1105,6 +1117,195 @@ public abstract class Strman {
return value.chars().mapToObj(ch -> leftPad(Integer.toString(ch, radix), "0", digits)).collect(joining());
}
/**
* Join concatenates all the elements of the strings array into a single String. The separator string is placed between elements in the resulting string.
*
* @param strings The input array to concatenate
* @param separator The separator to use
* @return Concatenated String
*/
public static String join(final String[] strings, final String separator) throws IllegalArgumentException {
if (strings == null) {
throw new IllegalArgumentException("Input array 'strings' can't be null");
}
if (separator == null) {
throw new IllegalArgumentException("separator can't be null");
}
StringJoiner joiner = new StringJoiner(separator);
for (String el : strings) {
joiner.add(el);
}
return joiner.toString();
}
/**
* Converts the first character of string to upper case and the remaining to lower case.
*
* @param input The string to capitalize
* @return The capitalized string
*/
public static String capitalize(final String input) throws IllegalArgumentException {
if (input == null) {
throw new IllegalArgumentException("input can't be null");
}
if (input.length() == 0) {
return "";
}
return head(input)
.map(String::toUpperCase)
.map(h ->
tail(input).map(t -> h + t.toLowerCase()).orElse(h))
.get();
}
/**
* Converts the first character of string to lower case.
*
* @param input The string to convert
* @return The converted string
* @throws IllegalArgumentException
*/
public static String lowerFirst(final String input) throws IllegalArgumentException {
if (input == null) {
throw new IllegalArgumentException("input can't be null");
}
if (input.length() == 0) {
return "";
}
return head(input)
.map(String::toLowerCase)
.map(h ->
tail(input).map(t -> h + t).orElse(h))
.get();
}
/**
* Verifies whether String is enclosed by encloser
*
* @param input The input String
* @param encloser String which encloses input String
* @return true if enclosed false otherwise
*/
public static boolean isEnclosedBetween(final String input, final String encloser) {
return isEnclosedBetween(input, encloser, encloser);
}
/**
* Verifies whether String is enclosed by encloser
*
* @param input The input String
* @param leftEncloser String which encloses input String at left start
* @param rightEncloser String which encloses input String at the right end
* @return true if enclosed false otherwise
*/
public static boolean isEnclosedBetween(final String input, final String leftEncloser, String rightEncloser) {
if (input == null) {
throw new IllegalArgumentException("input can't be null");
}
if (leftEncloser == null) {
throw new IllegalArgumentException("leftEncloser can't be null");
}
if (rightEncloser == null) {
throw new IllegalArgumentException("rightEncloser can't be null");
}
return input.startsWith(leftEncloser) && input.endsWith(rightEncloser);
}
/**
* Converts the first character of string to upper case.
*
* @param input The string to convert.
* @return Returns the converted string.
*/
public static String upperFirst(String input) {
if (input == null) {
throw new IllegalArgumentException("input can't be null");
}
return head(input)
.map(String::toUpperCase)
.map(h -> tail(input).map(t -> h + t).orElse(h))
.get();
}
/**
* Removes leading whitespace from string.
*
* @param input The string to trim.
* @return Returns the trimmed string.
*/
public static Optional<String> trimStart(final String input) {
return Optional.ofNullable(input)
.filter(v -> !v.isEmpty())
.map(Strman::leftTrim);
}
/**
* Removes leading characters from string.
*
* @param input The string to trim.
* @param chars The characters to trim.
*
* @return Returns the trimmed string.
*/
public static Optional<String> trimStart(final String input, String... chars) {
return Optional.ofNullable(input)
.filter(v -> !v.isEmpty())
.map(v -> {
String pattern = String.format("^[%s]+", join(chars, "\\"));
return v.replaceAll(pattern, "");
});
}
/**
* Removes trailing whitespace from string.
*
* @param input The string to trim.
* @return Returns the trimmed string.
*/
public static Optional<String> trimEnd(final String input) {
return Optional.ofNullable(input)
.filter(v -> !v.isEmpty())
.map(Strman::rightTrim);
}
/**
* Removes trailing characters from string.
*
* @param input The string to trim.
* @param chars The characters to trim.
*
* @return Returns the trimmed string.
*/
public static Optional<String> trimEnd(final String input, String... chars) {
return Optional.ofNullable(input)
.filter(v -> !v.isEmpty())
.map(v -> {
String pattern = String.format("[%s]+$", join(chars, "\\"));
return v.replaceAll(pattern, "");
});
}
/**
* Counts the number of occurrences of each character in the string
*
* @param input The input string
* @return A map containing the number of occurrences of each character in the string
*/
public static Map<Character, Long> charsCount(String input) {
if (isNullOrEmpty(input)) {
return Collections.emptyMap();
}
return input.chars()
.mapToObj(c -> (char) c)
.collect(groupingBy(identity(), counting()));
}
private static void validate(String value, Predicate<String> predicate, final Supplier<String> supplier) {
if (predicate.test(value)) {
throw new IllegalArgumentException(supplier.get());
@@ -1125,3 +1326,4 @@ public abstract class Strman {
return countSubstr(value.substring(offset), subStr, allowOverlapping, ++count);
}
}
+190 -8
View File
@@ -26,10 +26,10 @@
package strman;
import org.junit.Ignore;
import org.junit.Test;
import java.util.Arrays;
import java.util.Optional;
import java.util.*;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.CoreMatchers.*;
@@ -344,7 +344,7 @@ public class StrmanTest {
final String[] fixture = {
"foo", "foobar"
};
Arrays.stream(fixture).forEach(el -> assertThat(first(el, 3), equalTo("foo")));
Arrays.stream(fixture).forEach(el -> assertThat(first(el, 3), equalTo(Optional.of("foo"))));
}
@Test
@@ -353,7 +353,7 @@ public class StrmanTest {
"foo", "foobar"
};
Arrays.stream(fixture).forEach(el -> assertThat(head(el), equalTo("f")));
Arrays.stream(fixture).forEach(el -> assertThat(head(el), equalTo(Optional.of("f"))));
}
@Test
@@ -410,9 +410,9 @@ public class StrmanTest {
@Test
public void inequal_shouldTestInequalityOfStrings() throws Exception {
assertThat(inequal("a", "b"), equalTo(true));
assertThat(inequal("a", "a"), equalTo(false));
assertThat(inequal("0", "1"), equalTo(true));
assertThat(unequal("a", "b"), equalTo(true));
assertThat(unequal("a", "a"), equalTo(false));
assertThat(unequal("0", "1"), equalTo(true));
}
@Test
@@ -800,7 +800,8 @@ public class StrmanTest {
" de_camelize"
};
Arrays.stream(fixture).forEach(el -> assertThat(String.format("toKebabCase(%s) should be de-camelize", el), toKebabCase(el), equalTo("de-camelize")));
Arrays.stream(fixture).forEach(el ->
assertThat(String.format("toKebabCase(%s) should be de-camelize", el), toKebabCase(el), equalTo("de-camelize")));
}
@Test
@@ -845,4 +846,185 @@ public class StrmanTest {
String result = removeRight("Remove the END at the end", " END", false);
assertThat(result, is("Remove the END at the"));
}
@Test
public void transliterate_shouldDeburrTheString() throws Exception {
String result = transliterate("déjà vu");
assertThat(result, is(equalTo("deja vu")));
}
@Ignore
public void htmlEncode_shouldConvertCharactersToTheirHtmlEntities() throws Exception {
String result = htmlEncode("fred, barney, & pebbles");
assertThat(result, is(equalTo("fred, barney, &amp; pebbles")));
}
@Ignore
public void kebabCase_shouldConvertAStringToKebabCase() throws Exception {
String[] input = {
"Foo Bar",
"fooBar",
"__FOO_BAR__"
};
Arrays.stream(input).forEach(el ->
assertThat(String.format("%s should be foo-bar", el), toKebabCase(el), is(equalTo("foo-bar"))));
}
@Ignore
public void snakeCase_shouldConvertAStringToSnakecase() throws Exception {
String[] input = {
"Foo Bar",
"fooBar",
"--FOO-BAR--"
};
Arrays.stream(input).forEach(el ->
assertThat(String.format("%s should be foo_bar", el), toSnakeCase(el), is(equalTo("foo_bar"))));
}
@Test
public void join_shouldJoinArrayOfStringIntoASingleString() throws Exception {
String[] strings = {
"hello",
"world",
"123"
};
assertThat(join(strings, ";"), is(equalTo("hello;world;123")));
}
@Test(expected = IllegalArgumentException.class)
public void join_shouldThrowIllegalArgumentExceptionWhenSeparatorIsNull() throws Exception {
String[] strings = {
"hello",
"world",
"123"
};
join(strings, null);
}
@Test
public void join_shouldReturnEmptyStringWhenInputArrayIsEmpty() throws Exception {
String[] emptyArray = {};
assertThat(join(emptyArray, ","), is(equalTo("")));
}
@Test
public void capitalize_shouldCapitalizeFirstCharacterOfString() throws Exception {
String[] strings = {
"FRED",
"fRED",
"fred"
};
Arrays.stream(strings).forEach(el -> assertThat(String.format("%s should be Fred", el), capitalize(el), equalTo("Fred")));
}
@Test
public void lowerFirst_shouldLowercasedFirstCharacterOfString() throws Exception {
assertThat(lowerFirst("FRED"), is(equalTo("fRED")));
assertThat(lowerFirst("fred"), is(equalTo("fred")));
assertThat(lowerFirst("Fred"), is(equalTo("fred")));
}
@Test
public void isEnclosedBetween_shouldChekcWhetherStringIsEnclosed() throws Exception {
assertThat(isEnclosedBetween("{{shekhar}}", "{{", "}}"), is(true));
assertThat(isEnclosedBetween("shekhar", "{{", "}}"), is(false));
assertThat(isEnclosedBetween("*shekhar*", "*"), is(true));
assertThat(isEnclosedBetween("shekhar", "*"), is(false));
}
@Test(expected = IllegalArgumentException.class)
public void isEnclosedBetween_shouldThrowIllegalArgumentExceptionWhenEncloserIsNull() throws Exception {
assertThat(isEnclosedBetween("shekhar", null), is(false));
}
@Test
public void words_shouldConvertTextToWords() throws Exception {
final String line = "This is a string, with words!";
assertThat(words(line), is(new String[]{"This", "is", "a", "string", "with", "words"}));
}
@Test
public void upperFirst_shouldConvertFirstCharToUpperCase() throws Exception {
assertThat(upperFirst("fred"), is("Fred"));
}
@Test
public void upperFirst_shouldReturnSameStringIfFirstCharIsUpperCase() throws Exception {
assertThat(upperFirst("FRED"), is("FRED"));
}
@Test
public void trimStart_shouldRemoveAllWhitespaceAtStart() throws Exception {
assertThat(trimStart(" abc "), is(Optional.of("abc ")));
assertThat(trimStart("abc "), is(Optional.of("abc ")));
assertThat(trimStart("abc"), is(Optional.of("abc")));
assertThat(trimStart(""), is(Optional.empty()));
assertThat(trimStart(null), is(Optional.empty()));
}
@Test
public void trimStart_shouldRemoveSpecialCharactersAtStart() throws Exception {
assertThat(trimStart("-_-abc-_-", "_", "-"), is(Optional.of("abc-_-")));
assertThat(trimStart("-_-!abc-_-", "_", "-", "!"), is(Optional.of("abc-_-")));
assertThat(trimStart("-_-#abc-_-", "_", "-", "!", "#"), is(Optional.of("abc-_-")));
}
@Test
public void trimEnd_shouldRemoveAllTrailingWhitespace() throws Exception {
assertThat(trimEnd(" abc "), is(Optional.of(" abc")));
assertThat(trimEnd("abc "), is(Optional.of("abc")));
assertThat(trimEnd("abc"), is(Optional.of("abc")));
assertThat(trimEnd(""), is(Optional.empty()));
assertThat(trimEnd(null), is(Optional.empty()));
}
@Test
public void trimEnd_shouldRemoveAllTrailingSpecialCharacters() throws Exception {
assertThat(trimEnd("-_-abc-_-", "_", "-"), is(Optional.of("-_-abc")));
assertThat(trimEnd("-_-abc!-_-", "_", "-", "!"), is(Optional.of("-_-abc")));
assertThat(trimEnd("-_-abc#-_-", "_", "-", "!", "#"), is(Optional.of("-_-abc")));
}
@Test
public void charsCount_shouldReturnEmptyWhenInputStringIsNull(){
assertThat(charsCount(null), equalTo(Collections.emptyMap()));
}
@Test
public void charsCount_shouldReturnEmptyWhenInputStringIsEmpty(){
assertThat(charsCount(""), equalTo(Collections.emptyMap()));
}
@Test
public void charsCount_shouldReturnCharsCountWhenInputIsASimpleString(){
Map<Character, Long> expectedOutput = new HashMap<Character, Long>(){{
put('a',1L);
put('b', 1L);
put('c', 1L);
}};
assertThat(charsCount("abc"), equalTo(expectedOutput));
}
@Test
public void charsCount_shouldReturnCharsCountWhenInputIsAComplexString(){
Map<Character, Long> expectedOutput = new HashMap<Character, Long>(){{
put('a',1L);
put('b', 2L);
put('c', 3L);
put('A',1L);
put('B', 2L);
put('C', 3L);
put('-', 10L);
}};
assertThat(charsCount("-----abbcccCCCBBA-----"), equalTo(expectedOutput));
}
}