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 common string operations including validation, concatenation, padding, templating, and encoding conversions.
Main Features
- String validation and empty checks
- URL path concatenation
- String templating with placeholders
- String padding and formatting
- List/array joining with custom delimiters
- UTF-8 encoding/decoding utilities
- Pattern matching and replacement
Constants
EMPTY_STRING
- Empty string constantDELIM_STR
- Default template delimiter "{}"
Methods
1. Validation
hasText(String str)
- Check if string contains actual textisEmptyText(String str)
- Opposite of hasText()
2. Concatenation
concatUrl(String a, String b)
- Smart URL path concatenationjoin(T[] arr, String str)
- Join array with delimiterjoin(List<T> list, String str)
- Join list with delimiterjoin(List<String> list, String tpl, String str)
- Join with template formatting
3. Templating
print(String tpl, Object... args)
- Simple {} placeholder replacementsimpleTpl(String template, Map<String, Object> params)
- ${var} replacementsimpleTpl2(String template, Map<String, Object> data)
- #{var} replacementsimpleTpl(String template, Object data)
- JavaBean property replacement
4. Utilities
charCount(String str, String _char)
- Count character occurrencesleftPad(String str, int len, String _char)
- Left pad stringisWordOneOfThem(String word, String[] arr)
- Check string in arraygetUTF8_Bytes(String str)
- Get UTF-8 bytesbyte2String(byte[] bytes)
- Convert bytes to UTF-8 stringbyte2String(String str)
- Re-encode string as UTF-8
Usage Examples
Validation
boolean valid = StrUtil.hasText(" test "); // true
boolean empty = StrUtil.isEmptyText(" "); // true
URL Concatenation
String url = StrUtil.concatUrl("http://example.com", "api");
// "http://example.com/api"
Templating
String result = StrUtil.print("Hello {}!", "World"); // "Hello World!"
String tpl = StrUtil.simpleTpl("Name: ${name}", Map.of("name", "John"));
// "Name: John"
Joining
String joined = StrUtil.join(List.of("a","b","c"), ","); // "a,b,c"
Encoding
byte[] bytes = StrUtil.getUTF8_Bytes("test");
String str = StrUtil.byte2String(bytes); // "test"
Conclusion
The StrUtil
class provides comprehensive utility methods for string manipulation, making common string operations more convenient in Java applications.