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(final String value) {
20 chars = new ArrayList<>(value.length());
21 for (final Character c : value.toCharArray())
25 public String2 addPrefix(final String prefix) {
27 for (final char c : prefix.toCharArray())
33 public String2 addSuffix(final String suffix) {
34 for (final char c : suffix.toCharArray())
41 * Cut given amount of characters from the left of the string.
43 * @param cutAmount of characters to cut
44 * @return part that was cut.
46 public String2 trimPrefix(final int cutAmount) {
48 int actualCutAmount = cutAmount;
50 if (actualCutAmount > getLength())
51 actualCutAmount = getLength();
53 chars.subList(0, actualCutAmount).clear();
58 public String2 trimPrefixIfExists(String prefix){
59 if (hasPrefix(prefix))
60 trimPrefix(prefix.length());
65 public String2 trimSuffixIfExists(String suffix){
66 if (hasSuffix(suffix))
67 trimSuffix(suffix.length());
72 public String2 trimSuffix(int charsToTrim) {
74 if (charsToTrim > chars.size()){
79 for (int i = 0; i<charsToTrim; i++)
80 chars.remove(chars.size()-1);
85 public boolean hasSuffix(String suffix) {
86 return contains(suffix, getLength() - suffix.length());
89 public boolean hasPrefix(String prefix){
90 return contains(prefix, 0);
93 public boolean contains(String fragment, int index){
94 if (index + fragment.length() > chars.size())
97 for (int i = 0; i < fragment.length(); i++)
98 if (chars.get(index + i) != fragment.charAt(i))
104 public String2 enforceLength(final int targetLength) {
105 if (getLength() > targetLength)
106 chars.subList(targetLength, getLength()).clear();
107 else if (getLength() < targetLength) {
108 final int charactersToAdd = targetLength - getLength();
109 for (int i = 0; i < charactersToAdd; i++)
116 public int getLength() {
120 public String getSubString(final int startInclusive, final int endExclusive) {
121 final char[] charArray = new char[endExclusive - startInclusive];
124 for (int i = startInclusive; i < endExclusive; i++) {
125 charArray[j] = chars.get(i);
128 return new String(charArray);
131 public boolean isEmpty() {
132 return chars.size() == 0;
136 public String toString() {
137 return getSubString(0, chars.size());