-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringUtils.java
More file actions
69 lines (63 loc) · 2.25 KB
/
StringUtils.java
File metadata and controls
69 lines (63 loc) · 2.25 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
65
66
67
68
69
/**
* StringUtils - Utility class for common String manipulations.
* Focuses on null-safe operations and text formatting.
*/
public final class StringUtils {
// Private constructor to prevent instantiation
private StringUtils() {
throw new UnsupportedOperationException("Utility class");
}
/**
* Checks if a string is null or consists only of whitespace.
* @param str the string to check
* @return true if the string is null, empty, or whitespace
*/
public static boolean isBlank(String str) {
return str == null || str.trim().isEmpty();
}
/**
* Capitalizes the first letter of a string.
* @param str the string to capitalize
* @return the capitalized string, or the original if empty/null
*/
public static String capitalize(String str) {
if (isBlank(str)) return str;
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
/**
* Truncates a string to a specific length and adds an ellipsis (...) if truncated.
* @param str the string to truncate
* @param maxLength the maximum allowed length (including dots)
* @return the truncated string
*/
public static String abbreviate(String str, int maxLength) {
if (str == null || str.length() <= maxLength) return str;
if (maxLength < 3) return str.substring(0, maxLength);
return str.substring(0, maxLength - 3) + "...";
}
/**
* Reverses the characters in a string.
* @param str the string to reverse
* @return the reversed string, or null if input was null
*/
public static String reverse(String str) {
if (str == null) return null;
return new StringBuilder(str).reverse().toString();
}
/**
* Counts how many times a substring appears in a larger string.
* @param str the main string
* @param sub the substring to look for
* @return the number of occurrences
*/
public static int countOccurrences(String str, String sub) {
if (isBlank(str) || isBlank(sub)) return 0;
int count = 0;
int lastIndex = 0;
while ((lastIndex = str.indexOf(sub, lastIndex)) != -1) {
count++;
lastIndex += sub.length();
}
return count;
}
}