mirror of
https://github.com/shekhargulati/strman-java.git
synced 2026-10-21 06:54:09 +00:00
Added at function
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
package strman;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.StringJoiner;
|
||||
|
||||
/**
|
||||
@@ -26,7 +27,7 @@ public interface Strman {
|
||||
* @param appends an array of strings to append
|
||||
* @return full String
|
||||
*/
|
||||
static String appendArray(String value, String[] appends) {
|
||||
static String appendArray(final String value, final String[] appends) {
|
||||
if (value == null) {
|
||||
throw new IllegalArgumentException("'value' should be not null.");
|
||||
}
|
||||
@@ -39,4 +40,24 @@ public interface Strman {
|
||||
}
|
||||
return value + joiner.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the character at index. This method will take care of negative indexes.
|
||||
* The valid value of index is between -(length-1) to (length-1).
|
||||
* For values which don't fall under this range Optional.empty will be returned.
|
||||
*
|
||||
* @param value input value
|
||||
* @param index location
|
||||
* @return an Optional String if found else empty
|
||||
*/
|
||||
static Optional<String> at(final String value, int index) {
|
||||
if (value == null || value.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
int length = value.length();
|
||||
if (index < 0) {
|
||||
index = length + index;
|
||||
}
|
||||
return (index < length && index >= 0) ? Optional.of(String.valueOf(value.charAt(index))) : Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,10 +2,13 @@ package strman;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static strman.Strman.append;
|
||||
import static strman.Strman.appendArray;
|
||||
import static strman.Strman.at;
|
||||
|
||||
public class StrmanTest {
|
||||
|
||||
@@ -28,11 +31,18 @@ public class StrmanTest {
|
||||
assertThat(appendArray("", new String[]{"foobar"}), equalTo("foobar"));
|
||||
}
|
||||
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void appendArrayShouldThrowIllegalArgumentExceptionWhenValueIsNull() throws Exception {
|
||||
appendArray(null, new String[]{});
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void shouldFindCharacterAtIndex() throws Exception {
|
||||
assertThat(at("foobar", 0), equalTo(Optional.of("f")));
|
||||
assertThat(at("foobar", 1), equalTo(Optional.of("o")));
|
||||
assertThat(at("foobar", -1), equalTo(Optional.of("r")));
|
||||
assertThat(at("foobar", -2), equalTo(Optional.of("a")));
|
||||
assertThat(at("foobar", 10), equalTo(Optional.empty()));
|
||||
assertThat(at("foobar", -10), equalTo(Optional.empty()));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user