-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathStringUtils.java
More file actions
64 lines (56 loc) · 2.43 KB
/
StringUtils.java
File metadata and controls
64 lines (56 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package org.variantsync.diffdetective.util;
import java.util.Collection;
import java.util.regex.Pattern;
/** A collection of useful utilities related to string processing. */
public class StringUtils {
/** An operating system independent line break used in almost all internal strings. */
public final static String LINEBREAK = "\n";
/** A regex to identify line breaks of any operating system .*/
public final static Pattern LINEBREAK_REGEX = Pattern.compile("\\r\\n|\\r|\\n");
/** Remove the content {@code builder} so it can be reused for a new string. */
public static void clear(final StringBuilder builder) {
// According to https://stackoverflow.com/questions/5192512/how-can-i-clear-or-empty-a-stringbuilder
builder.setLength(0);
}
/**
* Append a human readable string representation of {@code collection} to {@code b}.
*
* @param indent an indent prepended to all appended lines
* @param b a string builder on which result is appended
* @param os the collection to be pretty printed
*/
private static void prettyPrintNestedCollections(final String indent, final StringBuilder b, final Collection<?> os) {
b.append(indent).append("[").append(LINEBREAK);
final String childIndent = " " + indent;
for (final Object o : os) {
if (o instanceof Collection<?> oos) {
prettyPrintNestedCollections(childIndent, b, oos);
} else {
b.append(childIndent).append(o.toString());
}
b.append(",").append(LINEBREAK);
}
b.append(indent).append("]");
}
/** Returns a human readable string representation of {@code collection}. */
public static String prettyPrintNestedCollections(final Collection<?> collection) {
final StringBuilder b = new StringBuilder();
prettyPrintNestedCollections("", b, collection);
return b.toString();
}
public static String clamp(int maxlen, String s) {
return s.substring(0, Math.min(s.length(), maxlen));
}
/**
* @return the longest prefix of the given string that contains only of whitespace
*/
public static String getLeadingWhitespace(String s) {
if (s == null) return null;
if (s.isEmpty()) return "";
int i = 0;
while (i < s.length() && Character.isWhitespace(s.charAt(i))) {
++i;
}
return s.substring(0, i);
}
}