2 * Svjatoslav Commons - shared library of common functionality. Author: Svjatoslav Agejenko.
3 * This project is released under Creative Commons Zero (CC0) license.
5 package eu.svjatoslav.commons.string;
7 import java.util.ArrayList;
10 public class String2 {
12 private final List<Character> chars = new ArrayList<>();
14 public String2(String value) {
18 public String2 addPrefix(final String prefix) {
23 for (final char c : prefix.toCharArray())
29 public String2 addSuffix(final String suffix) {
33 for (final char c : suffix.toCharArray())
39 public String2 addSuffix(String separator, final String suffix) {
49 * Cut given amount of characters from the left of the string.
51 * @param cutAmount of characters to cut
52 * @return part that was cut.
54 public String2 trimPrefix(final int cutAmount) {
56 int actualCutAmount = cutAmount;
58 if (actualCutAmount > getLength())
59 actualCutAmount = getLength();
61 chars.subList(0, actualCutAmount).clear();
66 public String2 trimPrefixIfExists(String prefix) {
70 if (hasPrefix(prefix))
71 trimPrefix(prefix.length());
76 public String2 trimSuffixIfExists(String suffix) {
77 if (hasSuffix(suffix))
78 trimSuffix(suffix.length());
83 public String2 trimSuffix(int charsToTrim) {
85 if (charsToTrim > chars.size()) {
90 for (int i = 0; i < charsToTrim; i++)
91 chars.remove(chars.size() - 1);
96 public boolean hasSuffix(String suffix) {
97 return contains(suffix, getLength() - suffix.length());
100 public boolean hasPrefix(String prefix) {
101 return contains(prefix, 0);
104 public boolean contains(String fragment, int index) {
105 if (index + fragment.length() > chars.size())
108 for (int i = 0; i < fragment.length(); i++)
109 if (chars.get(index + i) != fragment.charAt(i))
115 public String2 enforceLength(final int targetLength) {
116 if (getLength() > targetLength)
117 chars.subList(targetLength, getLength()).clear();
118 else if (getLength() < targetLength) {
119 final int charactersToAdd = targetLength - getLength();
120 for (int i = 0; i < charactersToAdd; i++)
127 public int getLength() {
131 public String getSubString(final int startInclusive, final int endExclusive) {
132 final char[] charArray = new char[endExclusive - startInclusive];
135 for (int i = startInclusive; i < endExclusive; i++) {
136 charArray[j] = chars.get(i);
139 return new String(charArray);
142 public boolean isEmpty() {
143 return chars.size() == 0;
147 public String toString() {
148 return getSubString(0, chars.size());