Class OpenString
Provides comprehensive string operations including padding, truncation, transformation, etc.
提供全面的字符串操作,包括填充、截断、转换等。
Features | 主要功能:
- Padding and truncation - 填充和截断
- Case conversion - 大小写转换
- String manipulation - 字符串操作
- Substring extraction - 子串提取
- Validation and checking - 验证和检查
Usage Examples | 使用示例:
// Padding
String padded = OpenString.padLeft("42", 5, '0'); // "00042"
// Truncation
String truncated = OpenString.truncate("Hello World", 8); // "Hello..."
// Substring extraction
String between = OpenString.substringBetween("[hello]", "[", "]"); // "hello"
// Statistics
int count = OpenString.countMatches("banana", "an"); // 2
Security | 安全性:
- Thread-safe: Yes (stateless utility) - 线程安全: 是(无状态工具类)
- Null-safe: Yes - 空值安全: 是
- Since:
- JDK 25, opencode-base-string V1.0.0
- Author:
- Leon Soo www.LeonSoo.com
- See Also:
-
Method Summary
Modifier and TypeMethodDescriptionstatic Stringabbreviate(String str, int maxWidth) Abbreviate a string using ellipsis ("...") if it exceeds the maximum width.static Stringabbreviate(String str, int offset, int maxWidth) Abbreviate a string using ellipsis ("...") starting from an offset.static StringabbreviateMiddle(String str, String middle, int maxLength) static StringblankToNull(String str) Convert a blank string (null, empty, or whitespace only) tonull.static Stringcapitalize(String str) static StringCenter string within the given minimum length using the pad character.charFrequency(String str) static Stringstatic Stringstatic StringcommonPrefix(String... strs) static StringcommonSuffix(String... strs) static booleancontainsAny(String str, CharSequence... searchStrings) Check if a string contains any of the given search strings.static booleancontainsChinese(String str) static booleancontainsIgnoreCase(String str, String search) Check if a string contains another string, ignoring case.static booleancontainsNone(String str, String invalidChars) Check if a string contains none of the given invalid characters.static booleancontainsOnly(String str, String validChars) Check if a string contains only the given valid characters.static intcountMatches(String str, char ch) static intcountMatches(String str, String subStr) static StringdefaultIfBlank(String str, String defaultStr) static StringdefaultIfEmpty(String str, String defaultStr) static Stringdifference(String str1, String str2) static StringemptyToNull(String str) Convert an empty string tonull.static booleanendsWithAny(String str, String... suffixes) Check if a string ends with any of the given suffixes.static booleanendsWithIgnoreCase(String str, String suffix) Check if a string ends with a suffix, ignoring case.static StringensurePrefix(String str, String prefix) static StringensureSuffix(String str, String suffix) static StringensureWrap(String str, String wrap) static StringfirstNonBlank(String... strs) static StringfirstNonEmpty(String... strs) static StringFormat a string using SLF4J-style{}placeholders.static Stringstatic StringgetRepeatedPattern(String str) static intindexOfDifference(String str1, String str2) static intindexOfNth(String str, String subStr, int n) static booleanisAllChinese(String str) static booleanisAllLowerCase(String str) static booleanisAllUpperCase(String str) static booleanstatic booleanisAlphanumeric(String str) static booleanstatic booleanCheck if a string is blank (null, empty, or whitespace only).static booleanCheck if a string is empty (null or zero length).static booleanisMixedCase(String str) static booleanisNotBlank(String str) Check if a string is not blank.static booleanisNotEmpty(String str) Check if a string is not empty.static booleanstatic booleanisPalindrome(String str) static booleanstatic booleanisRepeated(String str) static StringJoin elements with a separator.static StringjoinSkipBlanks(String separator, CharSequence... elements) Join elements with a separator, skipping blank elements.static StringjoinSkipNulls(String separator, Object... elements) Join elements with a separator, skippingnullelements.static StringkeepAlphanumeric(String str) static StringkeepChinese(String str) static StringkeepDigits(String str) static StringkeepLetters(String str) static intlastIndexOfNth(String str, String subStr, int n) static StringGet the leftmostlengthcharacters of a string.static Stringstatic Stringstatic StringnullToEmpty(String str) Convert anullstring to an empty string.static StringPad string on the left to reach minimum length.static StringPad string on the right to reach minimum length.static Stringstatic StringremovePrefix(String str, String prefix) static StringremovePrefixIgnoreCase(String str, String prefix) Remove a prefix from a string, ignoring case.static StringremoveSpecialChars(String str) static StringremoveSuffix(String str, String suffix) static StringremoveSuffixIgnoreCase(String str, String suffix) Remove a suffix from a string, ignoring case.static StringremoveWhitespace(String str) static StringRepeat a string with a separator between each occurrence.static StringreplaceEach(String text, String[] searchList, String[] replacementList) Replace all occurrences of search strings with corresponding replacement strings in a single pass.static Stringstatic StringGet the rightmostlengthcharacters of a string.static Stringstatic Stringstatic StringSplit a string by separator, returning aList.splitToMap(String str, String entrySep, String kvSep) Split a string into a key-value map using entry and key-value separators.static booleanstartsWithAny(String str, String... prefixes) Check if a string starts with any of the given prefixes.static booleanstartsWithIgnoreCase(String str, String prefix) Check if a string starts with a prefix, ignoring case.static StringstripAccents(String str) static StringsubstringAfter(String str, String separator) static StringsubstringAfterLast(String str, String separator) static StringsubstringBefore(String str, String separator) static StringsubstringBeforeLast(String str, String separator) static StringsubstringBetween(String str, String open, String close) static String[]substringsBetween(String str, String open, String close) static Stringstatic StringtoTitleCase(String str) static Stringstatic Stringstatic StringtruncateByBytes(String str, int maxBytes, String charset) static StringtruncateMiddle(String str, int maxLength) static Stringuncapitalize(String str) static Stringstatic StringwordFrequency(String str) static Stringstatic String
-
Method Details
-
padLeft
Pad string on the left to reach minimum length. 在字符串左侧填充以达到最小长度。- Parameters:
str- the input string, may benull(returnsnullif so)minLength- the minimum desired length; must not be negativepadChar- the character to pad with- Returns:
- the padded string, or
nullif input wasnull - Throws:
IllegalArgumentException- if minLength is negative
-
padRight
Pad string on the right to reach minimum length. 在字符串右侧填充以达到最小长度。- Parameters:
str- the input string, may benull(returnsnullif so)minLength- the minimum desired length; must not be negativepadChar- the character to pad with- Returns:
- the padded string, or
nullif input wasnull - Throws:
IllegalArgumentException- if minLength is negative
-
center
Center string within the given minimum length using the pad character. 使用填充字符将字符串居中至给定的最小长度。- Parameters:
str- the input string, may benull(returnsnullif so)minLength- the minimum desired length; must not be negativepadChar- the character to pad with- Returns:
- the centered string, or
nullif input wasnull - Throws:
IllegalArgumentException- if minLength is negative
-
left
Get the leftmostlengthcharacters of a string. 获取字符串最左侧的length个字符。- Parameters:
str- the input string, may benull(returnsnullif so)length- the number of characters to extract; negative values returnnullinput unchanged- Returns:
- the leftmost characters, or
nullif input wasnull
-
right
Get the rightmostlengthcharacters of a string. 获取字符串最右侧的length个字符。- Parameters:
str- the input string, may benull(returnsnullif so)length- the number of characters to extract; negative values returnnullinput unchanged- Returns:
- the rightmost characters, or
nullif input wasnull
-
mid
-
truncate
-
truncate
-
truncateMiddle
-
truncateByBytes
-
capitalize
-
uncapitalize
-
swapCase
-
toTitleCase
-
reverse
-
shuffle
-
shuffle
-
countMatches
-
countMatches
-
charFrequency
-
wordFrequency
-
removeWhitespace
-
normalizeWhitespace
-
removeInvisibleChars
-
removeSpecialChars
-
keepDigits
-
keepLetters
-
keepAlphanumeric
-
keepChinese
-
isNumeric
-
isAlpha
-
isAlphanumeric
-
isAscii
-
containsChinese
-
isAllChinese
-
isAllLowerCase
-
isAllUpperCase
-
isMixedCase
-
isPalindrome
-
isPalindromeIgnoreCase
-
ensurePrefix
-
ensureSuffix
-
ensureWrap
-
removePrefix
-
removeSuffix
-
commonPrefix
-
commonSuffix
-
findAll
-
indexOfNth
-
lastIndexOfNth
-
substringBefore
-
substringAfter
-
substringBeforeLast
-
substringAfterLast
-
substringBetween
-
substringsBetween
-
wrap
-
wrap
-
unwrap
-
unwrap
-
chomp
-
chop
-
stripAccents
-
getDigits
-
rotate
-
difference
-
indexOfDifference
-
abbreviateMiddle
-
isRepeated
-
getRepeatedPattern
-
defaultIfBlank
-
defaultIfEmpty
-
firstNonBlank
-
firstNonEmpty
-
isBlank
Check if a string is blank (null, empty, or whitespace only). 检查字符串是否为空白(null、空字符串或仅包含空白字符)。Examples | 示例:
isBlank(null) = true isBlank("") = true isBlank(" ") = true isBlank("abc") = false- Parameters:
str- the string to check, may benull| 待检查的字符串,可为null- Returns:
trueif the string is null, empty, or whitespace only | 如果字符串为null、空或仅含空白则返回true- Since:
- JDK 25, opencode-base-string V1.0.3
-
isNotBlank
Check if a string is not blank. 检查字符串是否不为空白。Examples | 示例:
isNotBlank(null) = false isNotBlank("") = false isNotBlank(" ") = false isNotBlank("abc") = true- Parameters:
str- the string to check, may benull| 待检查的字符串,可为null- Returns:
trueif the string is not null, not empty, and not whitespace only | 如果字符串非null、非空且非纯空白则返回true- Since:
- JDK 25, opencode-base-string V1.0.3
-
isEmpty
Check if a string is empty (null or zero length). 检查字符串是否为空(null或长度为零)。Examples | 示例:
isEmpty(null) = true isEmpty("") = true isEmpty(" ") = false isEmpty("abc") = false- Parameters:
str- the string to check, may benull| 待检查的字符串,可为null- Returns:
trueif the string is null or empty | 如果字符串为null或空则返回true- Since:
- JDK 25, opencode-base-string V1.0.3
-
isNotEmpty
Check if a string is not empty. 检查字符串是否不为空。Examples | 示例:
isNotEmpty(null) = false isNotEmpty("") = false isNotEmpty(" ") = true isNotEmpty("abc") = true- Parameters:
str- the string to check, may benull| 待检查的字符串,可为null- Returns:
trueif the string is not null and not empty | 如果字符串非null且非空则返回true- Since:
- JDK 25, opencode-base-string V1.0.3
-
containsAny
Check if a string contains any of the given search strings. 检查字符串是否包含给定搜索字符串中的任意一个。Examples | 示例:
containsAny("hello world", "world", "foo") = true containsAny("hello", "foo", "bar") = false containsAny(null, "foo") = false- Parameters:
str- the string to check, may benull| 待检查的字符串,可为nullsearchStrings- the strings to search for | 要搜索的字符串- Returns:
trueif the string contains any of the search strings | 如果字符串包含任一搜索字符串则返回true- Since:
- JDK 25, opencode-base-string V1.0.3
-
containsNone
Check if a string contains none of the given invalid characters. 检查字符串是否不包含任何给定的无效字符。Examples | 示例:
containsNone("hello", "xyz") = true containsNone("hello", "hxyz") = false containsNone(null, "xyz") = true- Parameters:
str- the string to check, may benull| 待检查的字符串,可为nullinvalidChars- characters that should not appear | 不应出现的字符- Returns:
trueif the string contains none of the invalid characters | 如果字符串不包含任何无效字符则返回true- Since:
- JDK 25, opencode-base-string V1.0.3
-
containsOnly
Check if a string contains only the given valid characters. 检查字符串是否仅包含给定的有效字符。Examples | 示例:
containsOnly("aab", "abc") = true containsOnly("abd", "abc") = false containsOnly(null, "abc") = false- Parameters:
str- the string to check, may benull| 待检查的字符串,可为nullvalidChars- characters that are allowed | 允许的字符- Returns:
trueif the string contains only valid characters | 如果字符串仅包含有效字符则返回true- Since:
- JDK 25, opencode-base-string V1.0.3
-
containsIgnoreCase
Check if a string contains another string, ignoring case. 忽略大小写检查字符串是否包含另一个字符串。Examples | 示例:
containsIgnoreCase("Hello World", "hello") = true containsIgnoreCase("Hello World", "foo") = false containsIgnoreCase(null, "hello") = false- Parameters:
str- the string to check, may benull| 待检查的字符串,可为nullsearch- the string to search for, may benull| 要搜索的字符串,可为null- Returns:
trueif the string contains the search string ignoring case | 如果忽略大小写后字符串包含搜索字符串则返回true- Since:
- JDK 25, opencode-base-string V1.0.3
-
startsWithAny
Check if a string starts with any of the given prefixes. 检查字符串是否以给定前缀中的任意一个开头。Examples | 示例:
startsWithAny("hello", "he", "ho") = true startsWithAny("hello", "foo") = false startsWithAny(null, "he") = false- Parameters:
str- the string to check, may benull| 待检查的字符串,可为nullprefixes- the prefixes to check | 要检查的前缀- Returns:
trueif the string starts with any of the prefixes | 如果字符串以任一前缀开头则返回true- Since:
- JDK 25, opencode-base-string V1.0.3
-
endsWithAny
Check if a string ends with any of the given suffixes. 检查字符串是否以给定后缀中的任意一个结尾。Examples | 示例:
endsWithAny("hello", "lo", "la") = true endsWithAny("hello", "foo") = false endsWithAny(null, "lo") = false- Parameters:
str- the string to check, may benull| 待检查的字符串,可为nullsuffixes- the suffixes to check | 要检查的后缀- Returns:
trueif the string ends with any of the suffixes | 如果字符串以任一后缀结尾则返回true- Since:
- JDK 25, opencode-base-string V1.0.3
-
startsWithIgnoreCase
Check if a string starts with a prefix, ignoring case. 忽略大小写检查字符串是否以指定前缀开头。Examples | 示例:
startsWithIgnoreCase("Hello", "he") = true startsWithIgnoreCase("Hello", "HE") = true startsWithIgnoreCase("Hello", "foo") = false- Parameters:
str- the string to check, may benull| 待检查的字符串,可为nullprefix- the prefix to check, may benull| 要检查的前缀,可为null- Returns:
trueif the string starts with the prefix ignoring case | 如果忽略大小写后字符串以该前缀开头则返回true- Since:
- JDK 25, opencode-base-string V1.0.3
-
endsWithIgnoreCase
Check if a string ends with a suffix, ignoring case. 忽略大小写检查字符串是否以指定后缀结尾。Examples | 示例:
endsWithIgnoreCase("Hello", "LO") = true endsWithIgnoreCase("Hello", "lo") = true endsWithIgnoreCase("Hello", "foo") = false- Parameters:
str- the string to check, may benull| 待检查的字符串,可为nullsuffix- the suffix to check, may benull| 要检查的后缀,可为null- Returns:
trueif the string ends with the suffix ignoring case | 如果忽略大小写后字符串以该后缀结尾则返回true- Since:
- JDK 25, opencode-base-string V1.0.3
-
replaceEach
Replace all occurrences of search strings with corresponding replacement strings in a single pass. 单趟扫描替换所有搜索字符串为对应的替换字符串,不递归替换。This method scans the input text once and replaces each occurrence of a search string with the corresponding replacement. Replacements are not applied recursively.
本方法对输入文本进行单趟扫描,将每个搜索字符串替换为对应的替换字符串。替换不会递归应用。
Examples | 示例:
replaceEach("aabbcc", new String[]{"aa","bb"}, new String[]{"11","22"}) = "1122cc" replaceEach("abcde", new String[]{"ab","d"}, new String[]{"w","t"}) = "wcte"- Parameters:
text- the text to search and replace in, may benull| 要搜索替换的文本,可为nullsearchList- the strings to search for, may benull| 要搜索的字符串数组,可为nullreplacementList- the strings to replace them with, may benull| 替换字符串数组,可为null- Returns:
- the text with replacements applied, or original text if no replacements needed | 替换后的文本
- Throws:
IllegalArgumentException- if searchList and replacementList have different lengths | 如果搜索和替换数组长度不同- Since:
- JDK 25, opencode-base-string V1.0.3
-
format
Format a string using SLF4J-style{}placeholders. 使用SLF4J风格的{}占位符格式化字符串。Placeholders are replaced left-to-right with the provided arguments. Use
\{}to escape a placeholder (outputs literal{}). Excess arguments are ignored; insufficient arguments leave placeholders intact.占位符从左到右依次替换为提供的参数。 使用
\{}转义占位符(输出字面量{})。 多余参数被忽略;参数不足时保留未替换的占位符。Examples | 示例:
format("{} has {} items", "Alice", 3) = "Alice has 3 items" format("{} and {}", "A") = "A and {}" format("literal \\{}", "ignored") = "literal {}"- Parameters:
pattern- the pattern string with{}placeholders, may benull| 包含占位符的模式字符串,可为nullargs- the arguments to fill in placeholders | 用于填充占位符的参数- Returns:
- the formatted string, or
nullif pattern isnull| 格式化后的字符串,pattern为null时返回null - Since:
- JDK 25, opencode-base-string V1.0.3
-
nullToEmpty
Convert anullstring to an empty string. 将null字符串转换为空字符串。Examples | 示例:
nullToEmpty(null) = "" nullToEmpty("") = "" nullToEmpty("hello") = "hello"- Parameters:
str- the string, may benull| 字符串,可为null- Returns:
- the original string or empty string if null | 原字符串或null时返回空字符串
- Since:
- JDK 25, opencode-base-string V1.0.3
-
emptyToNull
Convert an empty string tonull. 将空字符串转换为null。Examples | 示例:
emptyToNull("") = null emptyToNull(null) = null emptyToNull("hello") = "hello" emptyToNull(" ") = " "- Parameters:
str- the string, may benull| 字符串,可为null- Returns:
nullif the string is empty, otherwise the original string | 字符串为空时返回null,否则返回原字符串- Since:
- JDK 25, opencode-base-string V1.0.3
-
blankToNull
Convert a blank string (null, empty, or whitespace only) tonull. 将空白字符串(null、空字符串或仅含空白字符)转换为null。Examples | 示例:
blankToNull("") = null blankToNull(" ") = null blankToNull(null) = null blankToNull("hello") = "hello"- Parameters:
str- the string, may benull| 字符串,可为null- Returns:
nullif the string is blank, otherwise the original string | 字符串为空白时返回null,否则返回原字符串- Since:
- JDK 25, opencode-base-string V1.0.3
-
repeat
Repeat a string with a separator between each occurrence. 使用分隔符重复字符串。Examples | 示例:
repeat("abc", ", ", 3) = "abc, abc, abc" repeat("x", "-", 1) = "x" repeat("x", "-", 0) = "" repeat(null, "-", 3) = null- Parameters:
str- the string to repeat, may benull| 要重复的字符串,可为nullseparator- the separator between repetitions | 重复之间的分隔符count- the number of repetitions;<= 0returns empty string | 重复次数;小于等于0返回空字符串- Returns:
- the repeated string with separators, or
nullif str isnull| 带分隔符的重复字符串,str为null时返回null - Since:
- JDK 25, opencode-base-string V1.0.3
-
removePrefixIgnoreCase
Remove a prefix from a string, ignoring case. 忽略大小写移除字符串的前缀。Examples | 示例:
removePrefixIgnoreCase("HelloWorld", "hello") = "World" removePrefixIgnoreCase("HelloWorld", "HELLO") = "World" removePrefixIgnoreCase("HelloWorld", "foo") = "HelloWorld"- Parameters:
str- the string, may benull| 字符串,可为nullprefix- the prefix to remove, may benull| 要移除的前缀,可为null- Returns:
- the string without the prefix, or original if no match | 移除前缀后的字符串,不匹配时返回原字符串
- Since:
- JDK 25, opencode-base-string V1.0.3
-
removeSuffixIgnoreCase
Remove a suffix from a string, ignoring case. 忽略大小写移除字符串的后缀。Examples | 示例:
removeSuffixIgnoreCase("HelloWorld", "world") = "Hello" removeSuffixIgnoreCase("HelloWorld", "WORLD") = "Hello" removeSuffixIgnoreCase("HelloWorld", "foo") = "HelloWorld"- Parameters:
str- the string, may benull| 字符串,可为nullsuffix- the suffix to remove, may benull| 要移除的后缀,可为null- Returns:
- the string without the suffix, or original if no match | 移除后缀后的字符串,不匹配时返回原字符串
- Since:
- JDK 25, opencode-base-string V1.0.3
-
split
Split a string by separator, returning aList. Null-safe. 按分隔符分割字符串,返回List。空值安全。Examples | 示例:
split("a,b,c", ",") = ["a", "b", "c"] split(null, ",") = [] split("", ",") = [""]- Parameters:
str- the string to split, may benull| 要分割的字符串,可为nullseparator- the separator string | 分隔符字符串- Returns:
- a list of split parts, never
null| 分割后的部分列表,不会返回null - Since:
- JDK 25, opencode-base-string V1.0.3
-
splitToMap
Split a string into a key-value map using entry and key-value separators. 使用条目分隔符和键值分隔符将字符串分割为键值映射。Examples | 示例:
splitToMap("a=1invalid input: '&b'=2", "invalid input: '&'", "=") = {a=1, b=2} splitToMap(null, "invalid input: '&'", "=") = {}- Parameters:
str- the string to split, may benull| 要分割的字符串,可为nullentrySep- the separator between entries | 条目之间的分隔符kvSep- the separator between key and value | 键值之间的分隔符- Returns:
- a map of key-value pairs, never
null| 键值对映射,不会返回null - Since:
- JDK 25, opencode-base-string V1.0.3
-
join
Join elements with a separator. 使用分隔符合并元素。Examples | 示例:
join(", ", "a", "b", "c") = "a, b, c" join(", ", "a", null, "c") = "a, null, c"- Parameters:
separator- the separator string | 分隔符字符串elements- the elements to join | 要合并的元素- Returns:
- the joined string | 合并后的字符串
- Since:
- JDK 25, opencode-base-string V1.0.3
-
joinSkipNulls
Join elements with a separator, skippingnullelements. 使用分隔符合并元素,跳过null元素。Examples | 示例:
joinSkipNulls(", ", "a", null, "c") = "a, c"- Parameters:
separator- the separator string | 分隔符字符串elements- the elements to join | 要合并的元素- Returns:
- the joined string without null elements | 跳过null后合并的字符串
- Since:
- JDK 25, opencode-base-string V1.0.3
-
joinSkipBlanks
Join elements with a separator, skipping blank elements. 使用分隔符合并元素,跳过空白元素。Examples | 示例:
joinSkipBlanks(", ", "a", "", " ", "c") = "a, c"- Parameters:
separator- the separator string | 分隔符字符串elements- the elements to join | 要合并的元素- Returns:
- the joined string without blank elements | 跳过空白后合并的字符串
- Since:
- JDK 25, opencode-base-string V1.0.3
-
abbreviate
Abbreviate a string using ellipsis ("...") if it exceeds the maximum width. 当字符串超过最大宽度时使用省略号("...")进行简写。Examples | 示例:
abbreviate("Hello World", 8) = "Hello..." abbreviate("Hi", 8) = "Hi" abbreviate(null, 8) = null- Parameters:
str- the string to abbreviate, may benull| 要简写的字符串,可为nullmaxWidth- the maximum width; must be>= 4| 最大宽度;必须>= 4- Returns:
- the abbreviated string | 简写后的字符串
- Throws:
IllegalArgumentException- if maxWidth is less than 4 | 如果maxWidth小于4- Since:
- JDK 25, opencode-base-string V1.0.3
-
abbreviate
Abbreviate a string using ellipsis ("...") starting from an offset. 从指定偏移位置开始使用省略号("...")简写字符串。If the offset is greater than 0 and the string needs abbreviation, the result may start with "..." to indicate truncation from the left.
如果偏移量大于0且字符串需要简写,结果可能以"..."开头表示左侧被截断。
Examples | 示例:
abbreviate("Hello World Test", 0, 11) = "Hello Wo..." abbreviate("Hello World Test", 6, 11) = "...orld ..." abbreviate(null, 0, 8) = null- Parameters:
str- the string to abbreviate, may benull| 要简写的字符串,可为nulloffset- the left edge of the source string; if positive and truncation is needed, prepends "..." | 源字符串的左边缘偏移maxWidth- the maximum width; must be>= 4| 最大宽度;必须>= 4- Returns:
- the abbreviated string | 简写后的字符串
- Throws:
IllegalArgumentException- if maxWidth is less than 4 | 如果maxWidth小于4- Since:
- JDK 25, opencode-base-string V1.0.3
-