2 * Svjatoslav Commons - shared library of common functionality.
3 * Copyright ©2012-2019, 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 = new ArrayList<>();
19 public String2(String value) {
23 public String2 addPrefix(final String prefix) {
28 for (final char c : prefix.toCharArray())
34 public String2 addSuffix(final String suffix) {
38 for (final char c : suffix.toCharArray())
44 public String2 addSuffix(String separator, final String suffix) {
54 * Cut given amount of characters from the left of the string.
56 * @param cutAmount of characters to cut
57 * @return part that was cut.
59 public String2 trimPrefix(final int cutAmount) {
61 int actualCutAmount = cutAmount;
63 if (actualCutAmount > getLength())
64 actualCutAmount = getLength();
66 chars.subList(0, actualCutAmount).clear();
71 public String2 trimPrefixIfExists(String prefix) {
75 if (hasPrefix(prefix))
76 trimPrefix(prefix.length());
81 public String2 trimSuffixIfExists(String suffix) {
82 if (hasSuffix(suffix))
83 trimSuffix(suffix.length());
88 public String2 trimSuffix(int charsToTrim) {
90 if (charsToTrim > chars.size()) {
95 for (int i = 0; i < charsToTrim; i++)
96 chars.remove(chars.size() - 1);
101 public boolean hasSuffix(String suffix) {
102 return contains(suffix, getLength() - suffix.length());
105 public boolean hasPrefix(String prefix) {
106 return contains(prefix, 0);
109 public boolean contains(String fragment, int index) {
110 if (index + fragment.length() > chars.size())
113 for (int i = 0; i < fragment.length(); i++)
114 if (chars.get(index + i) != fragment.charAt(i))
120 public String2 enforceLength(final int targetLength) {
121 if (getLength() > targetLength)
122 chars.subList(targetLength, getLength()).clear();
123 else if (getLength() < targetLength) {
124 final int charactersToAdd = targetLength - getLength();
125 for (int i = 0; i < charactersToAdd; i++)
132 public int getLength() {
136 public String getSubString(final int startInclusive, final int endExclusive) {
137 final char[] charArray = new char[endExclusive - startInclusive];
140 for (int i = startInclusive; i < endExclusive; i++) {
141 charArray[j] = chars.get(i);
144 return new String(charArray);
147 public boolean isEmpty() {
148 return chars.size() == 0;
152 public String toString() {
153 return getSubString(0, chars.size());