StrUtil Tutorial
This tutorial provides an overview of the StrUtil class, which is part of the lightweight-component/aj-util library. The StrUtil class provides utility methods for string manipulation in Java applications.
Introduction
The StrUtil class contains static methods for counting, padding, templating, joining, and membership checks.
Main Features
- String templating with placeholders
- String padding and formatting
- List/array joining with custom delimiters
Methods
1. Joining
join(T[] arr, String str)- Join an array with a delimiterjoin(List<String> list, String str)- Join a string list with a delimiterjoin(List<String> list, String tpl, String str)- Format and join a string list
Array and list overloads serialize a null element as an empty string.
3. Templating
simpleTpl(String template, Map<String, Object> params)-${var}replacementsimpleTpl2(String template, Map<String, Object> data)-#{var}replacementsimpleTpl(String template, Object data)- JavaBean property replacement
Replacement values are treated literally, so $ and \ are safe in values. JavaBean templating skips write-only
properties. If a getter fails, the thrown RuntimeException identifies the property and retains the getter failure
as its cause.
4. Utilities
charCount(String str, String _char)- Count occurrences, including overlapping matchesleftPad(String str, int len, String padding)- Pad to exactlylencharacters without changing whitespace already instrisWordOneOfThem(String word, String[] arr)- Check string in array
Usage Examples
Templating
Map<String, Object> values = new HashMap<>();
values.put("name", "John");
String tpl = StrUtil.simpleTpl("Name: ${name}", values);
// "Name: John"
Counting and padding
int count = StrUtil.charCount("aaa", "aa"); // 2: overlapping matches are counted
String padded = StrUtil.leftPad("a b", 6, "$"); // "$$$a b"
Joining
String joined = StrUtil.join(Arrays.asList("a", "b", "c"), ","); // "a,b,c"
Conclusion
The StrUtil class provides comprehensive utility methods for string manipulation, making common string operations more convenient in Java applications.