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 repeat(int count){
19 String value = toString();
21 for (int i = 1; i < count; i++) {
27 public String2 addPrefix(final String prefix) {
32 for (final char c : prefix.toCharArray())
38 public String2 addSuffix(final String suffix) {
42 for (final char c : suffix.toCharArray())
48 public String2 addSuffix(String separator, final String suffix) {
58 * Cut given amount of characters from the left of the string.
60 * @param cutAmount of characters to cut
61 * @return part that was cut.
63 public String2 trimPrefix(final int cutAmount) {
65 int actualCutAmount = cutAmount;
67 if (actualCutAmount > getLength())
68 actualCutAmount = getLength();
70 chars.subList(0, actualCutAmount).clear();
75 public String2 trimPrefixIfExists(String prefix) {
79 if (hasPrefix(prefix))
80 trimPrefix(prefix.length());
85 public String2 trimSuffixIfExists(String suffix) {
86 if (hasSuffix(suffix))
87 trimSuffix(suffix.length());
92 public String2 trimSuffix(int charsToTrim) {
94 if (charsToTrim > chars.size()) {
99 for (int i = 0; i < charsToTrim; i++)
100 chars.remove(chars.size() - 1);
105 public boolean hasSuffix(String suffix) {
106 return contains(suffix, getLength() - suffix.length());
109 public boolean hasPrefix(String prefix) {
110 return contains(prefix, 0);
113 public boolean contains(String fragment, int index) {
114 if (index + fragment.length() > chars.size())
117 for (int i = 0; i < fragment.length(); i++)
118 if (chars.get(index + i) != fragment.charAt(i))
124 public String2 enforceLength(final int targetLength) {
125 if (getLength() > targetLength)
126 chars.subList(targetLength, getLength()).clear();
127 else if (getLength() < targetLength) {
128 final int charactersToAdd = targetLength - getLength();
129 for (int i = 0; i < charactersToAdd; i++)
136 public int getLength() {
140 public String getSubString(final int startInclusive, final int endExclusive) {
141 final char[] charArray = new char[endExclusive - startInclusive];
144 for (int i = startInclusive; i < endExclusive; i++) {
145 charArray[j] = chars.get(i);
148 return new String(charArray);
151 public boolean isEmpty() {
152 return chars.size() == 0;
156 public String toString() {
157 return getSubString(0, chars.size());