package eu.svjatoslav.commons.string;
-import java.util.Vector;
+import java.util.ArrayList;
+import java.util.List;
public class String2 {
- private final Vector<Character> chars = new Vector<>();
+ private final List<Character> chars;
public String2(final String value) {
+ chars = new ArrayList<>(value.length());
for (final Character c : value.toCharArray())
chars.add(c);
}
public String2 addPrefix(final String prefix) {
- int j = 0;
+ int i = 0;
for (final char c : prefix.toCharArray())
- chars.insertElementAt(c, j++);
+ chars.add(i++, c);
return this;
}
* @param cutAmount of characters to cut
* @return part that was cut.
*/
- public String trimLeft(final int cutAmount) {
+ public String2 trimPrefix(final int cutAmount) {
int actualCutAmount = cutAmount;
if (actualCutAmount > getLength())
actualCutAmount = getLength();
- final String result = getSubString(0, actualCutAmount);
-
chars.subList(0, actualCutAmount).clear();
- return result;
+ return this;
+ }
+
+ public String2 trimPrefixIfExists(String prefix){
+ if (hasPrefix(prefix))
+ trimPrefix(prefix.length());
+
+ return this;
+ }
+
+ public String2 trimSuffixIfExists(String suffix){
+ if (hasSuffix(suffix))
+ trimSuffix(suffix.length());
+
+ return this;
+ }
+
+ public String2 trimSuffix(int charsToTrim) {
+
+ if (charsToTrim > chars.size()){
+ chars.clear();
+ return this;
+ }
+
+ for (int i = 0; i<charsToTrim; i++)
+ chars.remove(chars.size()-1);
+
+ return this;
+ }
+
+ public boolean hasSuffix(String suffix) {
+ return contains(suffix, getLength() - suffix.length());
+ }
+
+ public boolean hasPrefix(String prefix){
+ return contains(prefix, 0);
+ }
+
+ public boolean contains(String fragment, int index){
+ if (index + fragment.length() > chars.size())
+ return false;
+
+ for (int i = 0; i < fragment.length(); i++)
+ if (chars.get(index + i) != fragment.charAt(i))
+ return false;
+
+ return true;
}
public String2 enforceLength(final int targetLength) {
public class String2Test {
@Test
- public void testCutLeft() {
+ public void testTrimPrefix() {
final String2 s = new String2("this is a test");
- assertEquals("this ", s.trimLeft(5));
- assertEquals("is ", s.trimLeft(3));
- assertEquals("a ", s.trimLeft(2));
- assertEquals("test", s.trimLeft(25));
- assertEquals("", s.trimLeft(5));
+ assertEquals("is a test", s.trimPrefix(5).toString());
+ assertEquals("a test", s.trimPrefix(3).toString());
+ assertEquals("test", s.trimPrefix(2).toString());
+ assertEquals("", s.trimPrefix(500).toString());
+ }
+
+ @Test
+ public void testTrimSuffix() {
+ final String2 s = new String2("this is a test");
+
+ assertEquals("this is a", s.trimSuffix(5).toString());
+ assertEquals("this is", s.trimSuffix(2).toString());
+ assertEquals("this", s.trimSuffix(3).toString());
+ assertEquals("", s.trimSuffix(500).toString());
}
+
@Test
public void testEnforceLength() {
final String2 s = new String2("12345678");