首页 > 代码库 > guava的String之Splitter

guava的String之Splitter

1.常用方法

摘自官网的部分常用方法说明。

Base Factories

MethodDescriptionExample
Splitter.on(char)Split on occurrences of a specific, individual character.Splitter.on(‘;‘)
Splitter.on(CharMatcher)Split on occurrences of any character in some category.Splitter.on(CharMatcher.BREAKING_WHITESPACE)
Splitter.on(CharMatcher.anyOf(";,."))
Splitter.on(String)Split on a literal String.Splitter.on(", ")
Splitter.on(Pattern)
Splitter.onPattern(String)
Split on a regular expression.Splitter.onPattern("\r?\n")
Splitter.fixedLength(int)Splits strings into substrings of the specified fixed length. The last piece can be smaller than length, but will never be empty.Splitter.fixedLength(3)

Modifiers

MethodDescriptionExample
omitEmptyStrings()Automatically omits empty strings from the result.Splitter.on(‘,‘).omitEmptyStrings().
split("a,,c,d")
 returns "a", "c", "d"
trimResults()Trims whitespace from the results; equivalent totrimResults(CharMatcher.WHITESPACE).Splitter.on(‘,‘).trimResults().split
("a, b, c, d")
 returns "a", "b", "c", "d"
trimResults(CharMatcher)Trims characters matching the specified CharMatcher from results.Splitter.on(‘,‘).trimResults
(CharMatcher.is(‘_‘)).split("_a ,_b_ ,c__")
 returns "a ", "b_ ", "c".
limit(int)Stops splitting after the specified number of strings have been returned.Splitter.on(‘,‘).limit(3).split
("a,b,c,d")
 returns "a", "b", "c,d"

2.实例

<script src="https://code.csdn.net/snippets/335599.js" type="text/javascript"></script>
运行结果:
根据分隔符进行分割:
a


-b
 c
-d
去掉分割后空的字符串:
a
-b
 c
-d
去掉分后后字符串中的空格:
a
-b
c
-d
去掉分后后字符串中‘-‘:
a
b
 c
d
以固定长度进行分割:
a,
,-
b,
c
,-
d
Splitter将处理结果处理成map类型:
key=a;value=http://www.mamicode.com/c
key=quzer;value=http://www.mamicode.com/yuanrq
key= ;value=http://www.mamicode.com/
key=hello;value=http://www.mamicode.com/csdn