Class String2
String2 provides a more intuitive alternative to StringBuilder
for operations involving prefixes and suffixes. It uses a fluent API
that allows method chaining for concise string manipulation.
Key features:
prepend(String)- Add text at the beginningappend(String)- Add text at the endtrimPrefix(int)- Remove characters from the beginningtrimSuffix(int)- Remove characters from the endtrimPrefixIfExists(String)- Remove prefix if presenttrimSuffixIfExists(String)- Remove suffix if presenthasPrefix(String)/hasSuffix(String)- Check for prefix/suffixrepeat(int)- Repeat the string contentenforceLength(int)- Pad or truncate to exact length
Example usage:
String2 s = new String2("world");
s.prepend("Hello, ").append("!");
// Result: "Hello, world!"
s.trimSuffix(1).append(" wonderful world!");
// Result: "Hello, world wonderful world!"
String2 path = new String2("/path/to/file");
path.trimPrefixIfExists("/").prepend("./");
// Result: "./path/to/file"
All methods (except getters) return the same String2 instance, enabling fluent method chaining:
String result = new String2()
.append("hello")
.appendWithSeparator(" ", "world")
.prepend("Say: ")
.append("!")
.toString();
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionAppends text at the end of this string.Appends the given string multiple times.appendWithSeparator(String separator, String suffix) Appends text with a separator, only adding the separator if the string is not empty.clear()Clears all characters from this string.booleanChecks if a fragment appears at the specified position in this string.enforceLength(int targetLength) Adjusts this string to have exactly the specified length.static String[]Extracts regex capture groups from a string.intReturns the current length of this string.getSubString(int startInclusive, int endExclusive) Returns a substring of this string.booleanChecks if this string starts with the specified prefix.booleanChecks if this string ends with the specified suffix.booleanisEmpty()Checks if this string is empty.Inserts text at the beginning of this string.repeat(int count) Repeats the current string content the specified number of times.toString()Returns the string content as a standard Java String.trimPrefix(int cutAmount) Removes the specified number of characters from the beginning of this string.trimPrefixIfExists(String prefix) Removes the specified prefix if this string starts with it.trimSuffix(int charsToTrim) Removes the specified number of characters from the end of this string.trimSuffixIfExists(String suffix) Removes the specified suffix if this string ends with it.
-
Constructor Details
-
String2
Creates a new String2 initialized with the given value.If the value is null, an empty String2 is created.
- Parameters:
value- the initial string content. May be null.
-
String2
public String2()Creates an empty String2.The string has zero length initially. Use
append(String)orprepend(String)to add content.
-
-
Method Details
-
clear
Clears all characters from this string.After calling this method, the string becomes empty (length 0). The fluent return allows immediate rebuilding of the string.
Example:
String2 s = new String2("hello"); s.clear().append("world"); // Result: "world"- Returns:
- this String2 instance for fluent method chaining.
-
repeat
Repeats the current string content the specified number of times.The string is duplicated and appended to itself.
- count = 1: no change (string remains as-is)
- count = 2: string appears twice
- count = 0 or negative: string is cleared
Example:
String2 s = new String2("ab"); s.repeat(3); // Result: "ababab" s.repeat(0); // Result: "" (empty)- Parameters:
count- the number of times to repeat the content. If less than 1, the string is cleared.- Returns:
- this String2 instance for fluent method chaining.
-
prepend
Inserts text at the beginning of this string.The prefix is added before all existing characters. If the prefix is null, no change occurs.
Example:
String2 s = new String2("world"); s.prepend("Hello, "); // Result: "Hello, world"- Parameters:
prefix- the text to prepend. May be null (no effect).- Returns:
- this String2 instance for fluent method chaining.
-
append
Appends text at the end of this string.The suffix is added after all existing characters. If the suffix is null, no change occurs.
Example:
String2 s = new String2("Hello"); s.append(", world!"); // Result: "Hello, world!"- Parameters:
suffix- the text to append. May be null (no effect).- Returns:
- this String2 instance for fluent method chaining.
-
appendWithSeparator
Appends text with a separator, only adding the separator if the string is not empty.This is useful for building comma-separated or space-separated lists where the separator should not appear before the first item.
Example:
String2 s = new String2(); s.appendWithSeparator(", ", "apple"); s.appendWithSeparator(", ", "banana"); s.appendWithSeparator(", ", "cherry"); // Result: "apple, banana, cherry"- Parameters:
separator- the separator to insert before the suffix if the string is not empty. Must not be null.suffix- the text to append. Must not be null.- Returns:
- this String2 instance for fluent method chaining.
-
append
Appends the given string multiple times.If times is zero, no change occurs. The string is appended repeatedly in sequence.
Example:
String2 s = new String2(); s.append("x", 5); // Result: "xxxxx"- Parameters:
s- the string to append repeatedly. Must not be null.times- the number of times to append. If zero, no change.- Returns:
- this String2 instance for fluent method chaining.
-
trimPrefix
Removes the specified number of characters from the beginning of this string.If cutAmount exceeds the string length, the entire string is cleared. If cutAmount is zero, no change occurs.
Example:
String2 s = new String2("hello world"); s.trimPrefix(6); // Result: "world" s.trimPrefix(500); // exceeds length // Result: "" (empty)- Parameters:
cutAmount- the number of characters to remove from the beginning.- Returns:
- this String2 instance for fluent method chaining.
-
trimPrefixIfExists
Removes the specified prefix if this string starts with it.If the string does not have the given prefix, no change occurs. If the prefix is null, no change occurs.
Example:
String2 s = new String2("prefix_content"); s.trimPrefixIfExists("prefix_"); // Result: "content" s.trimPrefixIfExists("nonexistent"); // Result: "content" (unchanged)- Parameters:
prefix- the prefix to remove if present. May be null (no effect).- Returns:
- this String2 instance for fluent method chaining.
-
trimSuffixIfExists
Removes the specified suffix if this string ends with it.If the string does not have the given suffix, no change occurs.
Note: This method may throw an exception if the suffix is longer than the string. Use carefully with potentially long suffix strings.
Example:
String2 s = new String2("content_suffix"); s.trimSuffixIfExists("_suffix"); // Result: "content"- Parameters:
suffix- the suffix to remove if present. Must not be null and must not be longer than the string.- Returns:
- this String2 instance for fluent method chaining.
-
trimSuffix
Removes the specified number of characters from the end of this string.If charsToTrim exceeds the string length, the entire string is cleared. If charsToTrim is zero, no change occurs.
Example:
String2 s = new String2("hello world"); s.trimSuffix(6); // Result: "hello" s.trimSuffix(500); // exceeds length // Result: "" (empty)- Parameters:
charsToTrim- the number of characters to remove from the end.- Returns:
- this String2 instance for fluent method chaining.
-
hasSuffix
Checks if this string ends with the specified suffix.Note: This method may throw an exception if the suffix is longer than the string. Ensure the suffix length is appropriate before calling.
Example:
String2 s = new String2("filename.txt"); s.hasSuffix(".txt"); // true s.hasSuffix("txt"); // true- Parameters:
suffix- the suffix to check for. Must not be null and must not be longer than the string.- Returns:
trueif this string ends with the suffix,falseotherwise.
-
hasPrefix
Checks if this string starts with the specified prefix.Example:
String2 s = new String2("Hello, world"); s.hasPrefix("Hello"); // true s.hasPrefix("hello"); // false (case-sensitive)- Parameters:
prefix- the prefix to check for. Must not be null.- Returns:
trueif this string starts with the prefix,falseotherwise.
-
contains
Checks if a fragment appears at the specified position in this string.This is a substring check starting at the given index. The fragment must match exactly (case-sensitive) at that position.
If the position plus fragment length exceeds the string length,
falseis returned.Example:
String2 s = new String2("hello world"); s.contains("hello", 0); // true s.contains("world", 6); // true s.contains("lo wo", 3); // true s.contains("hello", 1); // false- Parameters:
fragment- the text to check for. Must not be null.index- the starting position to check from (0-based).- Returns:
trueif the fragment appears at that position,falseotherwise.
-
enforceLength
Adjusts this string to have exactly the specified length.If the string is longer than the target, excess characters are removed from the end. If the string is shorter, spaces are added at the end. If the length already matches, no change occurs.
Example:
String2 s = new String2("12345678"); s.enforceLength(5); // Result: "12345" s.enforceLength(8); // Result: "12345 " (3 spaces added)This is useful for creating fixed-width columns or formatting text for tabular output.
- Parameters:
targetLength- the exact length to enforce.- Returns:
- this String2 instance for fluent method chaining.
-
getLength
public int getLength()Returns the current length of this string.- Returns:
- the number of characters in this string.
-
getSubString
Returns a substring of this string.The substring includes characters from startInclusive to endExclusive (exclusive end). This follows the standard Java substring convention.
Example:
String2 s = new String2("hello world"); s.getSubString(0, 5); // "hello" s.getSubString(6, 11); // "world"- Parameters:
startInclusive- the starting index (inclusive, 0-based).endExclusive- the ending index (exclusive). Must be greater than or equal to startInclusive.- Returns:
- the substring as a new String object.
-
isEmpty
public boolean isEmpty()Checks if this string is empty.- Returns:
trueif this string has zero length,falseotherwise.
-
toString
Returns the string content as a standard Java String.This creates a new String object containing all characters currently in this String2.
-
getGroups
Extracts regex capture groups from a string.This static utility method applies a regular expression to a string and returns all capture groups as an array.
Example:
String[] groups = String2.getGroups( "name: John, age: 25", "name: (\\w+), age: (\\d+)"); // groups[0] = "John" // groups[1] = "25"Note: The regex must match the string, otherwise this method will throw an exception. The returned array contains only capture groups (group 1 onwards), not the entire match.
- Parameters:
s- the string to search. Must not be null.regexp- the regular expression with capture groups. Must not be null and must match the string.- Returns:
- an array of captured group strings. Length equals the number of capture groups in the regexp.
-