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 = 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) {
53 * Cut given amount of characters from the left of the string.
55 * @param cutAmount of characters to cut
56 * @return part that was cut.
58 public String2 trimPrefix(final int cutAmount) {
60 int actualCutAmount = cutAmount;
62 if (actualCutAmount > getLength())
63 actualCutAmount = getLength();
65 chars.subList(0, actualCutAmount).clear();
70 public String2 trimPrefixIfExists(String prefix){
74 if (hasPrefix(prefix))
75 trimPrefix(prefix.length());
80 public String2 trimSuffixIfExists(String suffix){
81 if (hasSuffix(suffix))
82 trimSuffix(suffix.length());
87 public String2 trimSuffix(int charsToTrim) {
89 if (charsToTrim > chars.size()){
94 for (int i = 0; i<charsToTrim; i++)
95 chars.remove(chars.size()-1);
100 public boolean hasSuffix(String suffix) {
101 return contains(suffix, getLength() - suffix.length());
104 public boolean hasPrefix(String prefix){
105 return contains(prefix, 0);
108 public boolean contains(String fragment, int index){
109 if (index + fragment.length() > chars.size())
112 for (int i = 0; i < fragment.length(); i++)
113 if (chars.get(index + i) != fragment.charAt(i))
119 public String2 enforceLength(final int targetLength) {
120 if (getLength() > targetLength)
121 chars.subList(targetLength, getLength()).clear();
122 else if (getLength() < targetLength) {
123 final int charactersToAdd = targetLength - getLength();
124 for (int i = 0; i < charactersToAdd; i++)
131 public int getLength() {
135 public String getSubString(final int startInclusive, final int endExclusive) {
136 final char[] charArray = new char[endExclusive - startInclusive];
139 for (int i = startInclusive; i < endExclusive; i++) {
140 charArray[j] = chars.get(i);
143 return new String(charArray);
146 public boolean isEmpty() {
147 return chars.size() == 0;
151 public String toString() {
152 return getSubString(0, chars.size());