String Utilities
Collection of string manipulation and validation utilities
Description
A utility class providing common string operations including validation, transformation, formatting, and parsing.
Features
- Email and URL validation
- String transformation (camelCase, snake_case, etc.)
- Truncation and padding
- Pattern matching
Code
import java.util.regex.Pattern;public class StringUtils { private static final Pattern EMAIL_PATTERN = Pattern.compile("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$"); public static boolean isValidEmail(String email) { return email != null && EMAIL_PATTERN.matcher(email).matches(); } public static String toCamelCase(String str) { if (str == null || str.isEmpty()) return str; String[] parts = str.split("[-_\\s]+"); StringBuilder result = new StringBuilder(parts[0].toLowerCase()); for (int i = 1; i < parts.length; i++) { if (!parts[i].isEmpty()) { result.append(Character.toUpperCase(parts[i].charAt(0))); result.append(parts[i].substring(1).toLowerCase()); } } return result.toString(); } public static String truncate(String str, int maxLength, String suffix) { if (str == null || str.length() <= maxLength) return str; return str.substring(0, maxLength - suffix.length()) + suffix; } public static String padLeft(String str, int length, char padChar) { if (str == null) str = ""; if (str.length() >= length) return str; return String.valueOf(padChar).repeat(length - str.length()) + str; }}
import static StringUtils.*;public class Example { public static void main(String[] args) { String email = "[email protected]"; System.out.println("Email valid: " + isValidEmail(email)); String input = "hello-world-example"; System.out.println("Camel case: " + toCamelCase(input)); String text = "This is a very long string that needs truncation"; System.out.println("Truncated: " + truncate(text, 20, "...")); String number = "42"; System.out.println("Padded: " + padLeft(number, 5, '0')); }}
Comments
No comments yet. Be the first to comment!
Please login to leave a comment.