6 Commits
Author SHA1 Message Date
lizho d0c2a10a62 Update Strman.java (#97)
* Update Strman.java

fix bug in between()

* Update StrmanTests.java

* Update StrmanTests.java
2017-11-10 11:29:03 +05:30
Francesca Guiducci 9fb07aa1f8 Add escapeRegExp function (#95) 2017-10-22 13:09:40 +05:30
vic-nik da85915b8d Partially resolved #78 (#96)
* Partially resolved #78 (Hacktoberfest initiative)

* Removing trailing whitespaces
2017-10-22 13:09:20 +05:30
Francesca Guiducci befff2625b Add startCase function (#94) 2017-10-20 01:12:13 +05:30
Shekhar Gulati 7b552eb25b Updated README.md 2017-06-30 11:40:32 +05:30
Shekhar Gulati 099162d070 [Gradle Release Plugin] - new version commit: '0.5.0-SNAPSHOT'. 2017-06-30 11:27:38 +05:30
4 changed files with 111 additions and 622 deletions
+9 -617
View File
@@ -1,644 +1,36 @@
strman-java [![Build Status](https://travis-ci.org/shekhargulati/strman-java.svg?branch=master)](https://travis-ci.org/shekhargulati/strman-java) [![codecov.io](https://codecov.io/github/shekhargulati/strman-java/coverage.svg?branch=master)](https://codecov.io/github/shekhargulati/strman-java?branch=master) [![License](https://img.shields.io/:license-mit-blue.svg)](./LICENSE.txt) strman-java [![Build Status](https://travis-ci.org/shekhargulati/strman-java.svg?branch=master)](https://travis-ci.org/shekhargulati/strman-java) [![codecov.io](https://codecov.io/github/shekhargulati/strman-java/coverage.svg?branch=master)](https://codecov.io/github/shekhargulati/strman-java?branch=master) [![License](https://img.shields.io/:license-mit-blue.svg)](./LICENSE.txt)
------ ------
A Java 8 library for working with String. You can refer to Javadocs online [http://shekhargulati.github.io/strman-java/](http://shekhargulati.github.io/strman-java/). A Java 8 library for working with Strings.
You can learn about all the String utility functions implemented in `strman` library by reading the [documentation](https://github.com/shekhargulati/strman-java/wiki).
Getting Started Getting Started
-------- --------
To use strman in your application, you have to add `strman` in your classpath. strman is available on [Maven Central](http://search.maven.org/) so you just need to add dependency to your favorite build tool as show below. To use strman in your application, you have to add `strman` to your classpath.
strman is available on [Maven Central](http://search.maven.org/) so you just need to add dependency in your favorite build tool as shown below.
For Apache Maven users, please add following to your pom.xml. For Apache Maven users, please add following to your `pom.xml`.
```xml ```xml
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>com.shekhargulati</groupId> <groupId>com.shekhargulati</groupId>
<artifactId>strman</artifactId> <artifactId>strman</artifactId>
<version>0.3.0</version> <version>0.4.0</version>
</dependency> </dependency>
</dependencies> </dependencies>
``` ```
Gradle users can add following to their build.gradle file. Gradle users can add following to their `build.gradle` file.
``` ```
compile(group: 'com.shekhargulati', name: 'strman', version: '0.3.0') compile(group: 'com.shekhargulati', name: 'strman', version: '0.4.0')
``` ```
To learn what we added in the latest version please refer to `./changelog.md`. To learn what we added in the latest version please refer to `./changelog.md`.
## Available Functions You can refer to Javadocs online [http://shekhargulati.github.io/strman-java/](http://shekhargulati.github.io/strman-java/).
These are the available functions in current version of library:
## append
Appends Strings to value
```java
import static strman.Strman.append
append("f", "o", "o", "b", "a", "r")
// result => "foobar"
```
## appendArray
Append an array of String to value
```java
import static strman.Strman.appendArray
appendArray("f", new String[]{"o", "o", "b", "a", "r"}
// result => "foobar"
```
## at
Get the character at index. This method will take care of negative indexes.
```java
import static strman.Strman.at
at("foobar", 0)
// result => Optional("f")
```
## between
Returns an array with strings between start and end.
```java
import static strman.Strman.between
between("[abc][def]", "[", "]")
// result => ["abc","def"]
```
## chars
Returns a String array consisting of the characters in the String.
```java
import static strman.Strman.chars
chars("title")
// result => ["t", "i", "t", "l", "e"]
```
## charsCount
Counts the number of occurrences of each character in the string
```java
import static strman.Strman.charsCount
charsCount("abca")
// result => Map(("a",2),("b",1),("c",1))
```
## collapseWhitespace
Replace consecutive whitespace characters with a single space.
```java
import static strman.Strman.collapseWhitespace
collapseWhitespace("foo bar")
// result => "foo bar"
```
## contains
Verifies that the needle is contained in the value.
```java
import static strman.Strman.contains
contains("foo bar","foo")
// result => true
contains("foo bar","FOO", false) // turning off case sensitivity
// result => true
```
## containsAll
Verifies that all needles are contained in value
```java
import static strman.Strman.containsAll
containsAll("foo bar", new String[]{"foo", "bar"})
// result => true
containsAll("foo bar", new String[]{"FOO", "bar"},false)
// result => true
```
## containsAny
Verifies that one or more of needles are contained in value.
```java
import static strman.Strman.containsAny
containsAny("bar foo", new String[]{"FOO", "BAR", "Test"}, true)
// result => true
```
## countSubstr
Count the number of times substr appears in value
```java
import static strman.Strman.countSubstr
countSubstr("aaaAAAaaa", "aaa")
// result => 2
countSubstr("aaaAAAaaa", "aaa", false, false)
// result => 3
```
## endsWith
Test if value ends with search.
```java
import static strman.Strman.endsWith
endsWith("foo bar", "bar")
// result => true
endsWith("foo Bar", "BAR", false)
// result => true
```
## ensureLeft
Ensures that the value begins with prefix. If it doesn't exist, it's prepended.
```java
import static strman.Strman.ensureLeft
ensureLeft("foobar", "foo")
// result => "foobar"
ensureLeft("bar", "foo")
// result => "foobar"
ensureLeft("foobar", "FOO", false)
// result => "foobar"
```
## base64Decode
Decodes data encoded with MIME base64
```java
import static strman.Strman.base64Decode
base64Decode("c3RybWFu")
// result => "strman"
```
## base64Encode
Encodes data with MIME base64.
```java
import static strman.Strman.base64Encode
base64Encode("strman")
// result => "c3RybWFu"
```
## binDecode
Convert binary unicode (16 digits) string to string chars
```java
import static strman.Strman.binDecode
binDecode("0000000001000001")
// result => "A"
```
## binEncode
Convert string chars to binary unicode (16 digits)
```java
import static strman.Strman.binEncode
binEncode("A")
// result => "0000000001000001"
```
## decDecode
Convert decimal unicode (5 digits) string to string chars
```java
import static strman.Strman.decDecode
decDecode("00065")
// result => "A"
```
## decEncode
Convert string chars to decimal unicode (5 digits)
```java
import static strman.Strman.decEncode
decEncode("A")
// result => "00065"
```
## ensureRight
Ensures that the value ends with suffix. If it doesn't, it's appended.
```java
import static strman.Strman.ensureRight
ensureRight("foo", "bar")
// result => "foobar"
ensureRight("foobar", "bar")
// result => "foobar"
ensureRight("fooBAR", "bar", false)
// result => "foobar"
```
## first
Returns the first n chars of String
```java
import static strman.Strman.first
first("foobar", 3)
// result => "foo"
```
## head
Return the first char of String
```java
import static strman.Strman.head
head("foobar")
// result => "f"
```
## hexDecode
Convert hexadecimal unicode (4 digits) string to string chars
```java
import static strman.Strman.hexDecode
hexDecode("0041")
// result => "A"
```
## hexEncode
Convert string chars to hexadecimal unicode (4 digits)
```java
import static strman.Strman.hexEncode
hexEncode("A")
// result => "0041"
```
## inequal
Tests if two Strings are inequal
```java
import static strman.Strman.inequal
inequal("a", "b")
// result => true
```
## insert
Inserts 'substr' into the 'value' at the 'index' provided.
```java
import static strman.Strman.insert
insert("fbar", "oo", 1)
// result => "foobar"
```
## last
Return the last n chars of String
```java
import static strman.Strman.last
last("foobarfoo", 3)
// result => "foo"
```
## leftPad
Returns a new string of a given length such that the beginning of the string is padded.
```java
import static strman.Strman.leftPad
leftPad("1", "0", 5)
// result => "00001"
```
## lastIndexOf
This method returns the index within the calling String object of the last occurrence of the specified value, searching backwards from the offset.
```java
import static strman.Strman.lastIndexOf
lastIndexOf("foobarfoobar", "F", false)
// result => 6
```
## leftTrim
Removes all spaces on left
```java
import static strman.Strman.leftTrim
leftTrim(" strman")
// result => "strman"
```
## prepend
Return a new String starting with prepends
```java
prepend("r", "f", "o", "o", "b", "a")
// "foobar"
```
## removeEmptyStrings
Remove empty Strings from string array
```java
removeEmptyStrings(new String[]{"aa", "", " ", "bb", "cc", null})
// result => ["aa", "bb", "cc"]
```
## removeLeft
Returns a new String with the prefix removed, if present.
```java
removeLeft("foofoo", "foo")
// "foo"
```
## removeNonWords
Remove all non word characters.
```java
removeNonWords("foo&bar-")
// result => "foobar"
```
## removeRight
Returns a new string with the 'suffix' removed, if present.
```java
removeRight("foobar", "bar")
// result => "foo"
removeRight("foobar", "BAR",false)
// result => "foo"
```
## removeSpaces
Remove all spaces and replace for value.
```java
removeSpaces("foo bar")
// result => "foobar"
```
## repeat
Returns a repeated string given a multiplier.
```
repeat("1", 3)
// result => "111"
```
## reverse
Reverse the input String
```java
reverse("foo")
// result => "oof"
```
## rightPad
Returns a new string of a given length such that the ending of the string is padded.
```java
rightPad("1", "0", 5)
// result => "10000"
```
## rightTrim
Remove all spaces on right.
```java
rightTrim("strman ")
// result => "strman"
```
## safeTruncate
Truncate the string securely, not cutting a word in half. It always returns the last full word.
```java
safeTruncate("foo bar", 4, ".")
// result => "foo."
safeTruncate("A Javascript string manipulation library.", 16, "...")
// result => "A Javascript..."
```
## truncate
Truncate the unsecured form string, cutting the independent string of required position.
```java
truncate("A Javascript string manipulation library.", 14, "...")
// result => "A Javascrip..."
```
## htmlDecode
Converts all HTML entities to applicable characters.
```java
htmlDecode("&SHcy;")
// result => Ш
```
## htmlEncode
Convert all applicable characters to HTML entities.
```java
htmlEncode("Ш")
// result => "&SHcy;"
```
## shuffle
It returns a string with its characters in random order.
```java
shuffle("shekhar")
```
## slugify
Convert a String to a slug
```java
slugify("foo bar")
// result => "foo-bar"
```
## transliterate
Remove all non valid characters. Example: change á => a or ẽ => e.
```java
transliterate("fóõ bár")
// result => "foo bar"
```
## trimEnd
Removes trailing characters from string.
```
trimEnd(" abc ")
// result => Optional(" abc")
trimEnd("")
// result Optional.empty()
```
## surround
Surrounds a 'value' with the given 'prefix' and 'suffix'.
```java
surround("div", "<", ">"
// result => "<div>s"
```
## tail
```java
tail("foobar")
// result => "oobar"
```
## toCamelCase
Transform to camelCase
```java
toCamelCase("CamelCase")
// result => "camelCase"
toCamelCase("camel-case")
// result => "camelCase"
```
## toStudlyCase
Transform to StudlyCaps.
```java
toStudlyCase("hello world")
// result => "HelloWorld"
```
## toDecamelize
Decamelize String
```java
toDecamelize("helloWorld",null)
// result => "hello world"
```
## toKebabCase
Transform to kebab-case.
```java
toKebabCase("hello World")
// result => "hello-world"
```
## toSnakeCase
Transform to snake_case.
```java
toSnakeCase("hello world")
// result => "hello_world"
```
## upperFirst
Converts the first character of string to upper case.
```java
upperFirst("fred")
// result => "Fred"
```
## words
Splits a String to words
```java
words("This is a string, with words!")
// result => ["This", "is", "a", "string", "with", "words"]
```
## isEnclosedBetween
Verifies whether String is enclosed by encloser
```java
isEnclosedBetween("{{shekhar}}", "{{", "}}")
// result => true
```
## join
Join concatenates all the elements of the strings array into a single String. The separator string is placed between elements in the resulting string.
```java
join(new String[]{"hello","world","123"}, ";")
// result => "hello;world;123")
```
## isBlank
isEmpty returns true if a string is blank or null and false otherwise.
```java
isBlank("")
// result => true)
isBlank(null)
// result => true)
isBlank("test")
// result => false)
```
## underscored
`underscored` function converts a camel or dashed string into an underscored one
```java
underscored("MozTransform")
// result => "moz_transform")
```
## Inspiration ## Inspiration
+1 -1
View File
@@ -1 +1 @@
version= 0.4.0 version= 0.5.0-SNAPSHOT
+46 -1
View File
@@ -115,7 +115,9 @@ public abstract class Strman {
validate(end, NULL_STRING_PREDICATE, () -> "'end' should be not null."); validate(end, NULL_STRING_PREDICATE, () -> "'end' should be not null.");
String[] parts = value.split(end); String[] parts = value.split(end);
return Arrays.stream(parts).map(subPart -> subPart.substring(subPart.indexOf(start) + start.length())) return Arrays.stream(parts)
.filter(subPart -> subPart.contains(start))
.map(subPart -> subPart.substring(subPart.indexOf(start) + start.length()))
.toArray(String[]::new); .toArray(String[]::new);
} }
@@ -1389,6 +1391,29 @@ public abstract class Strman {
return resultBuilder.toString(); return resultBuilder.toString();
} }
/**
* Returns a string representation of the number passed in where groups of three digits are delimited by comma
*
* @param number Input number
* @return formatted String
*/
public static String formatNumber(long number) {
String stringRepresentation = Long.toString(number);
StringBuilder sb = new StringBuilder();
int bound = stringRepresentation.length() - 1;
String delimiter = ",";
int counter = 0;
for (int i = bound; i >= 0; i--) {
char c = stringRepresentation.charAt(i);
if (i != bound && counter % 3 == 0) {
sb.append(delimiter);
}
sb.append(c);
counter++;
}
return sb.reverse().toString();
}
public static String[] chop(String input, int step) { public static String[] chop(String input, int step) {
if (input == null || input.length() == 0) { if (input == null || input.length() == 0) {
return EMPTY_ARRAY; return EMPTY_ARRAY;
@@ -1404,6 +1429,26 @@ public abstract class Strman {
.toArray(String[]::new); .toArray(String[]::new);
} }
/**
* Converts a String into its Start Case version
* https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage
*
* @param input The input String
* @return Start Case String
*/
public static String startCase(final String input) {
validate(input, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
// split into a word when we encounter a space, or an underscore, or a dash, or a switch from lower to upper case
String[] words = words(input, "\\s|_|-|(?<=[a-z])(?=[A-Z])");
return Arrays.stream(words).filter(w -> !w.trim().isEmpty())
.map(w -> upperFirst(w.toLowerCase())).collect(joining(" "));
}
public static String escapeRegExp(final String input) {
validate(input, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return input.replaceAll("[\\\\\\^\\$\\*\\+\\-\\?\\.\\|\\(\\)\\{\\}\\[\\]]", "\\\\$0");
}
private static void validate(String value, Predicate<String> predicate, final Supplier<String> supplier) { private static void validate(String value, Predicate<String> predicate, final Supplier<String> supplier) {
if (predicate.test(value)) { if (predicate.test(value)) {
throw new IllegalArgumentException(supplier.get()); throw new IllegalArgumentException(supplier.get());
+55 -3
View File
@@ -92,9 +92,9 @@ public class StrmanTests {
} }
@Test @Test
public void between_shouldReturnFullStringWhenStartAndEndDoesNotExist() throws Exception { public void between_shouldReturnEmptyArrayWhenStartAndEndDoesNotExist() throws Exception {
assertThat(between("[abc][def]", "{", "}"), arrayContaining("[abc][def]")); assertThat(between("[abc][def]", "{", "}").length, equalTo(0));
assertThat(between("", "{", "}"), arrayContaining("")); assertThat(between("", "{", "}").length, equalTo(0));
} }
@Test @Test
@@ -1186,4 +1186,56 @@ public class StrmanTests {
assertThat(chop("whitespace", 3).length, equalTo(4)); assertThat(chop("whitespace", 3).length, equalTo(4));
assertThat(chop("whitespace", 0)[0].length(), equalTo(10)); assertThat(chop("whitespace", 0)[0].length(), equalTo(10));
} }
@Test
public void formatNumber_shouldFormatNumberWithCommaDelimiter() throws Exception {
assertThat(formatNumber(1000), equalTo("1,000"));
assertThat(formatNumber(100000), equalTo("100,000"));
assertThat(formatNumber(10000000), equalTo("10,000,000"));
assertThat(formatNumber(100000000), equalTo("100,000,000"));
}
@Test(expected = IllegalArgumentException.class)
public void startCase_shouldThrowException() throws Exception {
startCase(null);
}
@Test
public void startCase_shouldStartCaseInputString() throws Exception {
assertThat(startCase(""), equalTo(""));
assertThat(startCase("ALL CAPS"), equalTo("All Caps"));
assertThat(startCase("camelCase"), equalTo("Camel Case"));
assertThat(startCase("kebab-case"), equalTo("Kebab Case"));
assertThat(startCase("Snake_case"), equalTo("Snake Case"));
assertThat(startCase(" spaces "), equalTo("Spaces"));
assertThat(startCase("spaces between words"), equalTo("Spaces Between Words"));
assertThat(startCase("--dashes--"), equalTo("Dashes"));
assertThat(startCase("dashes----between----words"), equalTo("Dashes Between Words"));
}
@Test(expected = IllegalArgumentException.class)
public void escapeRegExp_shouldThrowException() throws Exception {
escapeRegExp(null);
}
@Test
public void escapeRegExp_shouldEscapeRegExp() throws Exception {
assertThat(escapeRegExp("\\"), equalTo("\\\\"));
assertThat(escapeRegExp("^"), equalTo("\\^"));
assertThat(escapeRegExp("$"), equalTo("\\$"));
assertThat(escapeRegExp("*"), equalTo("\\*"));
assertThat(escapeRegExp("+"), equalTo("\\+"));
assertThat(escapeRegExp("-"), equalTo("\\-"));
assertThat(escapeRegExp("?"), equalTo("\\?"));
assertThat(escapeRegExp("."), equalTo("\\."));
assertThat(escapeRegExp("|"), equalTo("\\|"));
assertThat(escapeRegExp("("), equalTo("\\("));
assertThat(escapeRegExp(")"), equalTo("\\)"));
assertThat(escapeRegExp("{"), equalTo("\\{"));
assertThat(escapeRegExp("}"), equalTo("\\}"));
assertThat(escapeRegExp("["), equalTo("\\["));
assertThat(escapeRegExp("]"), equalTo("\\]"));
assertThat(escapeRegExp("How much is (2+3)? 5"), equalTo("How much is \\(2\\+3\\)\\? 5"));
assertThat(escapeRegExp("\\s|_|-|(?<=[a-z])(?=[A-Z])"), equalTo("\\\\s\\|_\\|\\-\\|\\(\\?<=\\[a\\-z\\]\\)\\(\\?=\\[A\\-Z\\]\\)"));
}
} }