2 * Svjatoslav Commons - shared library of common functionality.
3 * Copyright ©2012-2017, Svjatoslav Agejenko, svjatoslav@svjatoslav.eu
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of version 3 of the GNU Lesser General Public License
7 * or later as published by the Free Software Foundation.
10 package eu.svjatoslav.commons.string;
12 import java.util.ArrayList;
13 import java.util.List;
15 public class String2 {
17 private final List<Character> chars;
19 public String2(String value) {
23 chars = new ArrayList<>(value.length());
24 for (final Character c : value.toCharArray())
28 public String2 addPrefix(final String prefix) {
33 for (final char c : prefix.toCharArray())
39 public String2 addSuffix(final String suffix) {
43 for (final char c : suffix.toCharArray())
50 * Cut given amount of characters from the left of the string.
52 * @param cutAmount of characters to cut
53 * @return part that was cut.
55 public String2 trimPrefix(final int cutAmount) {
57 int actualCutAmount = cutAmount;
59 if (actualCutAmount > getLength())
60 actualCutAmount = getLength();
62 chars.subList(0, actualCutAmount).clear();
67 public String2 trimPrefixIfExists(String prefix){
71 if (hasPrefix(prefix))
72 trimPrefix(prefix.length());
77 public String2 trimSuffixIfExists(String suffix){
78 if (hasSuffix(suffix))
79 trimSuffix(suffix.length());
84 public String2 trimSuffix(int charsToTrim) {
86 if (charsToTrim > chars.size()){
91 for (int i = 0; i<charsToTrim; i++)
92 chars.remove(chars.size()-1);
97 public boolean hasSuffix(String suffix) {
98 return contains(suffix, getLength() - suffix.length());
101 public boolean hasPrefix(String prefix){
102 return contains(prefix, 0);
105 public boolean contains(String fragment, int index){
106 if (index + fragment.length() > chars.size())
109 for (int i = 0; i < fragment.length(); i++)
110 if (chars.get(index + i) != fragment.charAt(i))
116 public String2 enforceLength(final int targetLength) {
117 if (getLength() > targetLength)
118 chars.subList(targetLength, getLength()).clear();
119 else if (getLength() < targetLength) {
120 final int charactersToAdd = targetLength - getLength();
121 for (int i = 0; i < charactersToAdd; i++)
128 public int getLength() {
132 public String getSubString(final int startInclusive, final int endExclusive) {
133 final char[] charArray = new char[endExclusive - startInclusive];
136 for (int i = startInclusive; i < endExclusive; i++) {
137 charArray[j] = chars.get(i);
140 return new String(charArray);
143 public boolean isEmpty() {
144 return chars.size() == 0;
148 public String toString() {
149 return getSubString(0, chars.size());