Added underscored method with tests and documentation

This commit is contained in:
Andy Deese
2017-05-20 12:01:13 -04:00
parent 04b9f8a7b4
commit 6bbcb53138
3 changed files with 53 additions and 1 deletions
+10
View File
@@ -631,6 +631,16 @@ isBlank("test")
// result => false)
```
## underscored
underscored returns a string that represents the passed in string in all lowercase and underscores
between words.
```java
underscored("MozTransform")
// result => "moz_transform")
```
## Inspiration
This library is inspired by [dleitee/strman](https://github.com/dleitee/strman).
+27 -1
View File
@@ -1310,12 +1310,38 @@ public abstract class Strman {
* Checks if string is empty. This is a null safe check and will return true when string is null.
*
* @param input The input string
* @return true if string is null or empty
* @return true if input string is null or empty
*/
public static boolean isBlank(String input) {
return input == null || input.isEmpty();
}
/**
* Changes passed in string to all lower case and adds underscore between words.
*
* @param input The input string
* @return the input string in all lower case with underscores between words
*/
public static String underscored(String input) {
String result = null;
if (input != null) {
StringBuffer resultBuffer = new StringBuffer();
char[] inputArray = input.toCharArray();
for(int i = 0; i < inputArray.length; i++) {
char nextChar = inputArray[i];
if (Character.isUpperCase(nextChar)) {
//start new word
if (resultBuffer.length() != 0) {
resultBuffer.append("_");
}
}
resultBuffer.append(nextChar);
}
result = resultBuffer.toString().toLowerCase();
}
return result;
}
private static void validate(String value, Predicate<String> predicate, final Supplier<String> supplier) {
if (predicate.test(value)) {
throw new IllegalArgumentException(supplier.get());
+16
View File
@@ -1040,4 +1040,20 @@ public class StrmanTest {
public void isBlank_shouldReturnFalseIfNotEmpty() {
assertFalse(isBlank("ac"));
}
@Test
public void underscored_shouldReturnUnderscoredString() {
assertThat(underscored("MozTransform"), equalTo("moz_transform"));
}
@Test
public void underscored_shouldReturnEmptyStringIfEmptyStringPassedIn() {
assertThat(underscored(""), equalTo(""));
}
@Test
public void underscored_shouldReturnNullIfNullPassedIn() {
assertThat(underscored(null), equalTo(null));
}
}