public final class StringUtil extends Object
String
工具类,可以查询,截取,format.
区别在于,split 使用的是 正则表达式
Pattern.split(CharSequence)
分隔(特别注意,一些特殊字符 $|()[{^?*+\\ 需要转义才能做分隔符),而StringTokenizer
使用索引机制,在性能上 StringTokenizer更高
因此,在注重性能的场景,还是建议使用StringTokenizer
StringUtils.capitalize(String)
首字母大写StringUtils.uncapitalize(String)
单词首字母小写WordUtils.uncapitalize(String, char...)
如果要使用一段文字,每个单词首字母小写
String.String(byte[] )
和 String.String(byte[], Charset)
区别
String.String(byte[] )
其实调用了String.String(byte[], Charset)
;
先使用Charset.defaultCharset()
,如果有异常再用 ISO-8859-1, 具体参见 java.lang.StringCoding#decode(byte[], int, int)
StringBuffer
和 StringBuilder
和 String
对比
StringBuffer
字符串变量(线程安全)StringBuilder
字符串变量(非线程安全)String
字符串常量- 在大部分情况下
StringBuffer
>
String
- 在大部分情况下
StringBuilder
>
StringBuffer
要看虚拟机的实现.而且要联系上下文
- 假设:HotSpot1.6,之前没有创建过"xyz" 则创建2个,之前创建过"xyz"则只创建1个
- 假设:HotSpot1.7,之前不管有没有创建过"xyz" 都创建1个
要看虚拟机的实现
- 假设:HotSpot1.6,则false不相等
- 假设:HotSpot1.7,则在之前没有创建过"abcabc"时,true相等
replace
和 replaceAll
和
replaceFirst
区别:
字段 说明 replace(String, String, String)
将字符串中出现的target替换成replacement replaceAll(CharSequence, String, String)
regex是一个正则表达式,将字符串中匹配的子字符串替换为replacement String.replaceFirst(String, String)
和 replace(String, String, String)
类似,只不过只替换第一个出现的地方。对比以下代码:
StringUtil.replaceAll("SH1265,SH5951", "([a-zA-Z]+[0-9]+)", "'$1'") ='SH1265','SH5951' StringUtil.replace("SH1265,SH5951", "([a-zA-Z]+[0-9]+)", "'$1'") =SH1265,SH5951 "SH1265,SH5951".replaceFirst("([a-zA-Z]+[0-9]+)", "'$1'") ='SH1265',SH5951
StringTokenizer
,
"org.springframework.util.StringUtils#tokenizeToStringArray(String, String)",
"org.springframework.beans.factory.xml.BeanDefinitionParserDelegate#MULTI_VALUE_ATTRIBUTE_DELIMITERS",
StringUtils
,
"com.google.common.base.Strings"Modifier and Type | Method and Description |
---|---|
static String |
format(String format,
Object... args)
将各类数据,使用
String.format(String, Object...) 格式化为字符串. |
static byte[] |
getBytes(String value)
字符串转换成byte数组.
|
static byte[] |
getBytes(String value,
String charsetName)
字符串
value 转换成byte数组. |
static String |
newString(byte[] bytes,
String charsetType)
Constructs a new
String by decoding the specified array of bytes using the given charset. |
static <V> String |
replace(CharSequence templateString,
Map<String,V> valuesMap)
使用给定的字符串
templateString 作为模板,解析匹配的变量 . |
static String |
replace(String text,
String searchString,
String replacement)
将
text 中的 searchString 替换成 replacement . |
static String |
replaceAll(CharSequence content,
String regex,
String replacement)
使用给定的
replacement 替换 content 此字符串所有匹配给定的正则表达式 regex 的子字符串. |
static String[] |
split(String value,
String regexSpliter)
将字符串
value 使用分隔符 regexSpliter 分隔成 字符串数组. |
static String |
substring(String text,
int beginIndex)
[截取]从指定索引处(
beginIndex )的字符开始,直到此字符串末尾. |
static String |
substring(String text,
int startIndex,
int length)
[截取]从开始位置(
startIndex ),截取固定长度(length )字符串. |
static String |
substringLast(String text,
int lastLenth)
[截取]:获取文字最后位数
lastLenth 的字符串. |
static String |
substringWithoutLast(CharSequence text,
String lastString)
[截取]:去除最后的字符串
lastString . |
static String |
substringWithoutLast(String text,
int lastLenth)
[截取]:去除最后几位
lastLenth . |
static String[] |
tokenizeToStringArray(String str,
String delimiters)
使用StringTokenizer分隔给定的字符串到字符串数组,去除 tokens的空格并且忽略empty tokens.
|
static String[] |
tokenizeToStringArray(String str,
String delimiters,
boolean trimTokens,
boolean ignoreEmptyTokens)
使用StringTokenizer分隔给定的字符串到字符串数组.
|
public static String newString(byte[] bytes, String charsetType)
String
by decoding the specified array of bytes using the given charset.bytes
- The bytes to be decoded into characters, may be null
charsetType
- 字符编码,建议使用 CharsetType
定义好的常量String
decoded from the specified array of bytes using the given charset,
or null
if the input byte array was null
.String.String(byte[], String)
,
"org.apache.commons.lang3.StringUtils#toString(byte[], String)",
StringUtils.toEncodedString(byte[], Charset)
,
"org.apache.commons.codec.binary.StringUtils#newString(byte[], String)"public static byte[] getBytes(String value)
value
- 字符串value
是null,抛出 NullPointerException
String.getBytes()
public static byte[] getBytes(String value, String charsetName)
value
转换成byte数组.value
- 字符串charsetName
- 受支持的 charset 名称,比如 utf-8, CharsetType
value
是null,抛出 NullPointerException
charsetName
是null,抛出 NullPointerException
charsetName
是blank,抛出 IllegalArgumentException
String.getBytes(String)
public static String replace(String text, String searchString, String replacement)
text
中的 searchString
替换成 replacement
.
A
null
reference passed to this method is a no-op.StringUtil.replace(null, *, *) = null StringUtil.replace("", *, *) = "" StringUtil.replace("any", null, *) = "any" StringUtil.replace("any", *, null) = "any" StringUtil.replace("any", "", *) = "any" StringUtil.replace("aba", "a", null) = "aba" StringUtil.replace("aba", "a", "") = "b" StringUtil.replace("aba", "a", "z") = "zbz" StringUtil.replace("黑色/黄色/蓝色", "/", "_") = "黑色_黄色_蓝色" StringUtil.replace(null, "/", "_") = null StringUtil.replace("黑色/黄色/蓝色", "/", null) = "黑色/黄色/蓝色"此外注意的是:StringUtil.replace("SH1265,SH5951", "([a-zA-Z]+[0-9]+)", "'$1'") = SH1265,SH5951(注意和replaceAll(CharSequence, String, String)
的区别)
- 该替换从字符串的开头朝末尾执行,例如,用 "b" 替换字符串 "aaa" 中的 "aa" 将生成 "ba" 而不是 "ab".
- 虽然底层调用了
Matcher.replaceAll()
,但是使用了Matcher.quoteReplacement()
处理了特殊字符
text
- text to search and replace in, may be nullsearchString
- the String to search for, may be nullreplacement
- the String to replace it with, may be nulltext
是null,返回 nullsearchString
是null,原样返回 text
replacement
是null,原样返回 text
String.replace(CharSequence, CharSequence)
,
StringUtils.replace(String, String, String)
public static String replaceAll(CharSequence content, String regex, String replacement)
replacement
替换 content
此字符串所有匹配给定的正则表达式 regex
的子字符串.
- 此方法底层调用的是
Matcher.replaceAll(String)
,相同于Pattern.compile(regex).matcher(str).replaceAll(repl)
StringUtil.replaceAll("SH1265,SH5951,SH6766,SH7235,SH1265,SH5951,SH6766,SH7235", "([a-zA-Z]+[0-9]+)", "'$1'")返回:'SH1265','SH5951','SH6766','SH7235','SH1265','SH5951','SH6766','SH7235'
在替代字符串
replacement
中,使用 backslashes反斜杆(\)和 dollar signs美元符号 ($)与将其视为字面值替代字符串所得的结果可能不同.
请参阅Matcher.replaceAll
;如有需要,可使用Matcher.quoteReplacement
取消这些字符的特殊含义$ may be treated as references to captured subsequences as described above,$这个特殊的字符,因为替换串使用这个引用正则表达式匹配的组, $0代表匹配项,$1代表第1个匹配分组,$1代表第2个匹配分组
并且 \ are used to escape literal characters in the replacement string.
//分隔字符串并添加引号. public void splitAndAddYinHao(){ String a = "12345,56789,1123456"; String[] aStrings = a.split(","); StringBuilder sb = new StringBuilder(); int size = aStrings.length; for (int i = 0; i可以重构成:<
size; i++){ sb.append("'" + aStrings[i] + "'"); if (i != size - 1){ sb.append(","); } } LOGGER.debug(sb.toString()); }StringUtil.replaceAll("12345,56789,1123456", "([0-9]+)", "'$1'")结果都是:'12345','56789','1123456'
content
- 需要被替换的字符串regex
- 用来匹配此字符串的正则表达式,规则参见 "RegexPattern"注释replacement
- 用来替换每个匹配项的字符串content
是null,返回 StringUtils.EMPTY
content
中,没有 regex匹配的字符串或者格式,返回content
String.replaceAll(String, String)
public static <V> String replace(CharSequence templateString, Map<String,V> valuesMap)
templateString
作为模板,解析匹配的变量 .
String template = "/home/webuser/expressdelivery/${yearMonth}/${expressDeliveryType}/vipQuery_${fileName}.log"; Date date = now(); Map返回:<String, String>
valuesMap = newHashMap(); valuesMap.put("yearMonth", DateUtil.toString(date, DatePattern.YEAR_AND_MONTH)); valuesMap.put("expressDeliveryType", "sf"); valuesMap.put("fileName", DateUtil.toString(date, DatePattern.TIMESTAMP)); LOGGER.debug(StringUtil.replace(template, valuesMap));/home/webuser/expressdelivery/2016-06/sf/vipQuery_20160608214846.log
注意:此方法只能替换字符串,而不能像el表达式一样使用对象属性之类的来替换
Map返回:<String, Object>
valuesMap = newHashMap(); valuesMap.put("today", DateUtil.toString(now(), COMMON_DATE)); valuesMap.put("user", new User(1L)); LOGGER.debug(StringUtil.replace("${today}${today1}${user.id}${user}", valuesMap) + "");2016-07-16${today1}${user.id}com.feilong.test.User@16f9a31
V
- the value typetemplateString
- the template stringvaluesMap
- the values maptemplateString
是 StringUtils.isEmpty(templateString)
,返回 StringUtils.EMPTY
valuesMap
是null或者empty,原样返回 templateString
StrSubstitutor.replace(String)
,
StrSubstitutor.replace(Object, Map)
public static String substring(String text, int beginIndex)
beginIndex
)的字符开始,直到此字符串末尾.
如果 beginIndex
是负数,那么表示倒过来截取,从结尾开始截取长度,此时等同于 substringLast(String, int)
StringUtil.substring(null, *) = null StringUtil.substring("", *) = "" StringUtil.substring("abc", 0) = "abc" StringUtil.substring("abc", 2) = "c" StringUtil.substring("abc", 4) = "" StringUtil.substring("abc", -2) = "bc" StringUtil.substring("abc", -4) = "abc" StringUtil.substring("jinxin.feilong",6) =.feilong
text
- 内容 the String to get the substring from, may be nullbeginIndex
- 从指定索引处 the position to start from,negative means count back from the end of the String by this many characterstext
是null,返回 nullStringUtils.substring(String, int)
,
substringLast(String, int)
public static String substring(String text, int startIndex, int length)
startIndex
),截取固定长度(length
)字符串.
StringUtil.substring(null, 6, 8) = null StringUtil.substring("jinxin.feilong", 6, 2) = .f
text
- 被截取文字startIndex
- 索引开始位置,0开始length
- 长度 >=1
text
是null,返回 nullstartIndex + length
>
text.length
,那么截取 从 startIndex 开始截取,截取到最后StringUtils.substring(String, int, int)
public static String substringLast(String text, int lastLenth)
lastLenth
的字符串.
StringUtil.substringLast("jinxin.feilong", 5) = ilong
text
- 文字lastLenth
- 最后的位数text
是null,返回 nulllastLenth<0
,返回 StringUtils.EMPTY
text.length() <= lastLenth
,返回text text.substring(text.length() - lastLenth)
StringUtils.right(String, int)
public static String substringWithoutLast(String text, int lastLenth)
lastLenth
.
调用了 String.substring(int, int)
StringUtil.substringWithoutLast("jinxin.feilong", 5) //jinxin.fe
text
- 文字lastLenth
- 最后的位数text
是null,返回 StringUtils.EMPTY
String.substring(int, int)
,
StringUtils.left(String, int)
public static String substringWithoutLast(CharSequence text, String lastString)
lastString
.
StringUtil.substringWithoutLast(null, "222") = "" StringUtil.substringWithoutLast("jinxin.feilong", "ng") = "jinxin.feilo" StringUtil.substringWithoutLast("jinxin.feilong ", " ") = "jinxin.feilong"
text
- the textlastString
- the last stringtext
是null,返回 StringUtils.EMPTY
lastString
是null,返回 text.toString()
public static String[] split(String value, String regexSpliter)
value
使用分隔符 regexSpliter
分隔成 字符串数组.
建议使用 tokenizeToStringArray(String, String)
或者 StringUtils.split(String)
value
- valueregexSpliter
- 此处不是简单的分隔符,是正则表达式,.$|()[{^?*+\\ 有特殊的含义,因此我们使用.的时候必须进行转义,"\"转义时要写成"\\\\" Pattern.split(CharSequence)
value
是null或者empty,返回 ArrayUtils.EMPTY_STRING_ARRAY
String.split(String)
,
String.split(String, int)
,
StringUtils.split(String)
,
Pattern.split(CharSequence)
public static String[] tokenizeToStringArray(String str, String delimiters)
(此方法借鉴 "org.springframework.util.StringUtils#tokenizeToStringArray").
调用了 tokenizeToStringArray(String, String, boolean, boolean)
,本方法默认使用参数 trimTokens = true;
ignoreEmptyTokens = true;
String str = "jin.xin feilong ,jinxin;venusdrogon;jim "; String delimiters = ";, ."; String[] tokenizeToStringArray = StringUtil.tokenizeToStringArray(str, delimiters); LOGGER.info(JsonUtil.format(tokenizeToStringArray));返回:[ "jin", "xin", "feilong", "jinxin", "venusdrogon", "jim" ]
给定的delimiters字符串支持任意数量的分隔字符characters.
每一个characters可以用来分隔tokens.一个delimiter分隔符常常是一个single字符;
如果你要使用多字符 multi-character delimiters分隔, 你可以考虑使用delimitedListToStringArray
str
- 需要被分隔的字符串delimiters
- delimiter characters, assembled as Stringstr
是null,返回 ArrayUtils.EMPTY_STRING_ARRAY
str
是blank,返回 ArrayUtils.EMPTY_STRING_ARRAY
StringTokenizer
,
String.trim()
,
"org.springframework.util.StringUtils#delimitedListToStringArray",
"org.springframework.util.StringUtils#tokenizeToStringArray",
tokenizeToStringArray(String, String, boolean, boolean)
public static String[] tokenizeToStringArray(String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens)
(此方法借鉴 "org.springframework.util.StringUtils#tokenizeToStringArray").
给定的delimiters字符串支持任意数量的分隔字符characters.
每一个characters可以用来分隔tokens.一个delimiter分隔符常常是一个single字符;
如果你要使用多字符 multi-character delimiters分隔, 你可以考虑使用delimitedListToStringArray
StringTokenizer
:StringTokenizer
implementsEnumeration<Object>
其在 Enumeration接口的基础上,定义了 hasMoreTokens nextToken两个方法
实现的Enumeration接口中的 hasMoreElements nextElement,调用了 hasMoreTokens nextToken
str
- 需要被分隔的字符串delimiters
- delimiter characters, assembled as StringtrimTokens
- 是否使用 String.trim()
操作tokenignoreEmptyTokens
- 是否忽视空白的token,如果为true,那么token必须长度 >
0;如果为false会包含长度=0 空白的字符str
是null,返回 ArrayUtils.EMPTY_STRING_ARRAY
StringTokenizer
,
String.trim()
,
"org.springframework.util.StringUtils#delimitedListToStringArray",
"org.springframework.util.StringUtils#tokenizeToStringArray"public static String format(String format, Object... args)
String.format(String, Object...)
格式化为字符串.
对整数进行格式化:
由4部分组成:%[index$][标识][最小宽度]转换方式
此外,StringUtil.format("%03d", 1) 不能写成 StringUtil.format("%03d", "1")
对浮点数进行格式化:
%[index$][标识][最少宽度][.精度]转换方式
- %index$开头,index从1开始取值,表示将第index个参数拿进来进行格式化.
转换符和标志的说明:
转换符 说明 示例 %s 字符串类型 "mingrisoft" %c 字符类型 'm' %b 布尔类型 true %d 整数类型(十进制) 99 %x 整数类型(十六进制) FF %o 整数类型(八进制) 77 %f 浮点类型 99.99 %a 十六进制浮点类型 FF.35AE %e 指数类型 9.38e+5 %g 通用浮点类型(f和e类型中较短的) %h 散列码 %% 百分比类型 % %n 换行符 %tx 日期与时间类型(x代表不同的日期与时间转换符
标志 说明 示例 结果 + 为正数或者负数添加符号 ("%+d",15) +15 - 左对齐(不可以与"用0填充"同时使用) ("%-5d",15) |15 | 0 数字前面补0 ("%04d", 99) 0099 空格 在整数之前添加指定数量的空格 ("% 4d", 99) | 99| , 以","对数字分组 ("%,f", 9999.99) 9,999.990000 ( 使用括号包含负数 ("%(f", -99.99) (99.990000) # 如果是浮点数则包含小数点,如果是16进制或8进制则添加0x或0 ("%#x", 99)
("%#o", 99)0x63
0143<
格式化前一个转换符所描述的参数 ("%f和% <
3.2f", 99.45)99.450000和99.45 $ 被格式化的参数索引 ("%1$d,%2$s", 99,"abc") 99,abc
format
- the formatargs
- the argsformat
是null,返回 StringUtils.EMPTY
format
包含不需要转化的字符串,这些字符串是你写什么,最终就输出什么String.format(String, Object...)
Formatter
,
String.format(String, Object...)
,
String.format(java.util.Locale, String, Object...)
Copyright © 2008-2019 by feilong