public class StringUtils {
// Check if string is empty or null
public static boolean isEmpty(String str) {
return str == null || str.isEmpty();
}
// Check if string is blank (whitespace only)
public static boolean isBlank(String str) {
return str == null || str.trim().isEmpty();
}
// Reverse string
public static String reverse(String str) {
if (str == null) return null;
return new StringBuilder(str).reverse().toString();
}
// Count occurrences
public static int countOccurrences(String str, String substring) {
if (str == null || substring == null || substring.isEmpty()) {
return 0;
}
int count = 0;
int index = 0;
while ((index = str.indexOf(substring, index)) != -1) {
count++;
index += substring.length();
}
return count;
}
// Remove whitespace
public static String removeWhitespace(String str) {
if (str == null) return null;
return str.replaceAll("\\s+", "");
}
// Capitalize first letter
public static String capitalize(String str) {
if (isEmpty(str)) return str;
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
// Join strings
public static String join(String delimiter, String... strings) {
if (strings == null || strings.length == 0) return "";
StringBuilder result = new StringBuilder(strings[0]);
for (int i = 1; i < strings.length; i++) {
result.append(delimiter).append(strings[i]);
}
return result.toString();
}
// Truncate string
public static String truncate(String str, int maxLength) {
if (str == null || str.length() <= maxLength) return str;
return str.substring(0, maxLength) + "...";
}
}