其他分享
首页 > 其他分享> > guava包Strings工具类

guava包Strings工具类

作者:互联网

有时候我们在项目中需要拼接一组字符串,中间用分隔符连接。

但使用jdk,你不得对最后一个元素和前面的其他元素进行区分。

使用guava提供的工具类让这一切变得简单。

一、拼接字符串

Joiner joiner = Joiner.on("; ").skipNulls();
return joiner.join("Harry", null, "Ron", "Hermione");
//Harry; Ron; Hermione

Joiner.on(",").join(Arrays.asList(1, 5, 7)); // returns "1,5,7"

二、拆分字符串

拆分字符串是拼接字符串的逆向操作。jdk内置了对拆分字符串的操作方法String.split().

但当你面对的是不规则的内容时,这个工作并不简单。比如

  ",a,,b,".split(",")返回什么?

  1. "", "a", "", "b", ""
  2. null, "a", null, "b", null
  3. "a", null, "b"
  4. "a", "b"
  5. 以上都不是

正确答案是5,实际返回: "", "a", "", "b"

但是这真是我们想要的结果吗?

guava包Splitter允许你对拆分行为进行完全的控制以规避令人迷惑的结果。

Splitter.on(',')
    .trimResults()
    .omitEmptyStrings()
    .split("foo,bar,,   qux");
//[foo, bar, qux]

更多选择

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 to trimResults(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"

 

标签:Splitter,null,CharMatcher,trimResults,returns,split,工具,guava,Strings
来源: https://www.cnblogs.com/wangbin2188/p/15881873.html