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;
9 import java.util.regex.Matcher;
10 import java.util.regex.Pattern;
12 public class String2 {
14 private final List<Character> chars = new ArrayList<>();
16 public String2(String value) {
20 public String2 repeat(int count){
21 String value = toString();
23 for (int i = 1; i < count; i++) {
29 public String2 addPrefix(final String prefix) {
34 for (final char c : prefix.toCharArray())
40 public String2 addSuffix(final String suffix) {
44 for (final char c : suffix.toCharArray())
50 public String2 addSuffix(String separator, final String suffix) {
60 * Cut given amount of characters from the left of the string.
62 * @param cutAmount of characters to cut
63 * @return part that was cut.
65 public String2 trimPrefix(final int cutAmount) {
67 int actualCutAmount = cutAmount;
69 if (actualCutAmount > getLength())
70 actualCutAmount = getLength();
72 chars.subList(0, actualCutAmount).clear();
77 public String2 trimPrefixIfExists(String prefix) {
81 if (hasPrefix(prefix))
82 trimPrefix(prefix.length());
87 public String2 trimSuffixIfExists(String suffix) {
88 if (hasSuffix(suffix))
89 trimSuffix(suffix.length());
94 public String2 trimSuffix(int charsToTrim) {
96 if (charsToTrim > chars.size()) {
101 for (int i = 0; i < charsToTrim; i++)
102 chars.remove(chars.size() - 1);
107 public boolean hasSuffix(String suffix) {
108 return contains(suffix, getLength() - suffix.length());
111 public boolean hasPrefix(String prefix) {
112 return contains(prefix, 0);
115 public boolean contains(String fragment, int index) {
116 if (index + fragment.length() > chars.size())
119 for (int i = 0; i < fragment.length(); i++)
120 if (chars.get(index + i) != fragment.charAt(i))
126 public String2 enforceLength(final int targetLength) {
127 if (getLength() > targetLength)
128 chars.subList(targetLength, getLength()).clear();
129 else if (getLength() < targetLength) {
130 final int charactersToAdd = targetLength - getLength();
131 for (int i = 0; i < charactersToAdd; i++)
138 public int getLength() {
142 public String getSubString(final int startInclusive, final int endExclusive) {
143 final char[] charArray = new char[endExclusive - startInclusive];
146 for (int i = startInclusive; i < endExclusive; i++) {
147 charArray[j] = chars.get(i);
150 return new String(charArray);
153 public boolean isEmpty() {
154 return chars.size() == 0;
158 public String toString() {
159 return getSubString(0, chars.size());
163 public static String[] getGroups(String s, String regexp){
164 Pattern pattern = Pattern.compile(regexp);
165 Matcher matcher = pattern.matcher(s);
168 String[] result = new String[matcher.groupCount()];
170 for (int i = 0; i< result.length; i++){
171 result[i] = matcher.group(i+1);