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())
49 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());