Code cleanup and formatting. Migrated to java 1.8.
[svjatoslav_commons.git] / src / main / java / eu / svjatoslav / commons / string / String2.java
1 /*
2  * Svjatoslav Commons - shared library of common functionality.
3  * Copyright ©2012-2014, Svjatoslav Agejenko, svjatoslav@svjatoslav.eu
4  *
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.
8  */
9
10 package eu.svjatoslav.commons.string;
11
12 import java.util.Vector;
13
14 public class String2 {
15
16     private final Vector<Character> chars = new Vector<>();
17
18     public String2(final String value) {
19         for (final Character c : value.toCharArray())
20             chars.add(c);
21     }
22
23     public String2 addPrefix(final String prefix) {
24         int j = 0;
25         for (final char c : prefix.toCharArray())
26             chars.insertElementAt(c, j++);
27
28         return this;
29     }
30
31     public String2 addSuffix(final String suffix) {
32         for (final char c : suffix.toCharArray())
33             chars.add(c);
34
35         return this;
36     }
37
38     /**
39      * Cut given amount of characters from the left of the string.
40      *
41      * @param cutAmount of characters to cut
42      * @return part that was cut.
43      */
44     public String trimLeft(final int cutAmount) {
45
46         int actualCutAmount = cutAmount;
47
48         if (actualCutAmount > getLength())
49             actualCutAmount = getLength();
50
51         final String result = getSubString(0, actualCutAmount);
52
53         chars.subList(0, actualCutAmount).clear();
54
55         return result;
56     }
57
58     public String2 enforceLength(final int targetLength) {
59         if (getLength() > targetLength)
60             chars.subList(targetLength, getLength()).clear();
61         else if (getLength() < targetLength) {
62             final int charactersToAdd = targetLength - getLength();
63             for (int i = 0; i < charactersToAdd; i++)
64                 chars.add(' ');
65         }
66
67         return this;
68     }
69
70     public int getLength() {
71         return chars.size();
72     }
73
74     public String getSubString(final int startInclusive, final int endExclusive) {
75         final char[] charArray = new char[endExclusive - startInclusive];
76
77         int j = 0;
78         for (int i = startInclusive; i < endExclusive; i++) {
79             charArray[j] = chars.get(i);
80             j++;
81         }
82         return new String(charArray);
83     }
84
85     public boolean isEmpty() {
86         return chars.size() == 0;
87     }
88
89     @Override
90     public String toString() {
91         return getSubString(0, chars.size());
92     }
93 }