package com.google.common.base
类注释
- 通过识别分隔符(separator),从输入字符串中提取非重叠子字符串;分隔符可以是:char、String、regular expression或者CharMatcher
- 除了按照分隔符分割字符串,Splitter还可以从输入字符串中提取固定长度的子串
- 通常情况下,Splitter的行为是简易的,如:
Splitter.on(',').split(" foo,,, bar ,")
将会得到几个empty的字符串;可以指定Splitter的行为使之产出我们想要的结果:
private static final Splitter MY_SPLITTER = Splitter.on(',')
.trimResults()
.omitEmptyStrings();
MY_SPLITTER.split("foo,,, bar ,");
// 结果:["foo","bar"] - 警告:Splitter实例是不可变的且是线程安全的,调用配置方法对接收实例没有影响;必须存储和使用它返回的新的分离器实例
// Do NOT do this
Splitter splitter = Splitter.on('/');
splitter.trimResults(); // does nothing!
return splitter.split("wrong / wrong / wrong"); - Joiner类提供了拆分的逆操作,但是注意两者之间的往返应该被认为是有损的。
获取Splitter实例——策略模式(Strategy)
Splitter可以接受char、String、正则表达式或者是CharMattcher作为分隔符,包括fixedLength(从原字符串中截取若干固定长度的子串),不同的分隔符通过重载on方法、传入策略接口Strategy获取相应的实例:
可以发现:通过Splitter提供的私有构造方法
private Splitter(Strategy strategy) {
this(strategy, false, CharMatcher.none(), Integer.MAX_VALUE);
}
中传入自定义的策略接口Strategy,不同之处在于,各自实现接口的下面两个方法:
/**
* Returns the first index in {@code toSplit} at or after {@code start} that contains the
* separator.
*/
abstract int separatorStart(int start);
/**
* Returns the first index in {@code toSplit} after {@code
* separatorPosition} that does not contain a separator. This method is only invoked after a
* call to {@code separatorStart}.
*/
abstract int separatorEnd(int separatorPosition);
不同的分割策略(Strategy)对于上述两个方法的实现不同,而这两个方法的作用以及他们对computeNext()方法的影响,最终将影响字符串分割的结果。
所以现在分析的重点是:
- 1、separatorStart方法和separatorEnd方法的作用;
- 2、computeNext方法的作用;
- 3、上述3分方法之间的关系
separatorStart:返回原字符串(toSplit)中在start这个位置之后,分隔符(separator)出现的第一个位置的索引,注意参数start:这个索引要么在start处,要么在start之后(所以start这个参数很重要);
separatorEnd:返回原字符串中,在separatorPosition这个位置之后的、不包含分隔符的第一个索引。 此方法仅在调用separatorStart方法之后调用。
举例解释下:
toSplit ="abc;de;fgh;i";
separator是 “;”
那么,separatorStart(0) 返回的是 : 3,即第一个“;”的索引;
separatorEnd(3)返回的是 : 4
computeNext:源码如下
final CharSequence toSplit;
final CharMatcher trimmer;
final boolean omitEmptyStrings;
int offset = 0;
...
@Override
protected String computeNext() {
/*
* The returned string will be from the end of the last match to the beginning of the next
* one. nextStart is the start position of the returned substring, while offset is the place
* to start looking for a separator.
*/
int nextStart = offset;
while (offset != -1) {
int start = nextStart;
int end;
int separatorPosition = separatorStart(offset);
if (separatorPosition == -1) {
end = toSplit.length();
offset = -1;
} else {
end = separatorPosition;
offset = separatorEnd(separatorPosition);
}
if (offset == nextStart) {
/*
* This occurs when some pattern has an empty match, even if it doesn't match the empty
* string -- for example, if it requires lookahead or the like. The offset must be
* increased to look for separators beyond this point, without changing the start position
* of the next returned substring -- so nextStart stays the same.
*/
offset++;
if (offset >= toSplit.length()) {
offset = -1;
}
continue;
}
while (start < end && trimmer.matches(toSplit.charAt(start))) {
start++;
}
while (end > start && trimmer.matches(toSplit.charAt(end - 1))) {
end--;
}
if (omitEmptyStrings && start == end) {
// Don't include the (unused) separator in next split string.
nextStart = offset;
continue;
}
if (limit == 1) {
// The limit has been reached, return the rest of the string as the
// final item. This is tested after empty string removal so that
// empty strings do not count towards the limit.
end = toSplit.length();
offset = -1;
// Since we may have changed the end, we need to trim it again.
while (end > start && trimmer.matches(toSplit.charAt(end - 1))) {
end--;
}
} else {
limit--;
}
return toSplit.subSequence(start, end).toString();
}
return endOfData();
}
这个方法返回的字符串,是从上一个匹配的末尾(from the end of the last match)到下一个匹配的开始(the beginning of the next one),也就是说,执行这个方法,将原字符串中位于分隔符之间的子串一个一个提取出来;nextStart是返回的子字符串的开始位置,而offset是开始查找分隔符的位置。
这三个方法之间的关系:很明显,computeNext()方法用来迭代地将被分隔符分割的子串一个一个的提取出来,而separatorStart()方法和separatorEnd()方法为止提供了匹配开始和结束的索引位置。
所以我们回头再看看:不同的策略下,对separatorStart()方法和separatorEnd()方法的实现,到底对分割策略能有什么影响
-
Splitter on(final CharMatcher separatorMatcher)
// 返回了start之后(含)的分隔符在原字符串中出现的第一个索引位置 @Override int separatorStart(int start) { return separatorMatcher.indexIn(toSplit, start); } // 返回了上一个分隔符出现位置的后一个索引 @Override int separatorEnd(int separatorPosition) { return separatorPosition + 1; }
所以对于CharMatcher来说(char也被处理作CharMatcher),每一个字符的匹配都会被computeNext拿去计算下一个分割得到的子串。
-
Splitter on(final String separator)
// 会发现:这特么不就是一个搜索子串的算法么 @Override public int separatorStart(int start) { int separatorLength = separator.length(); positions: for (int p = start, last = toSplit.length() - separatorLength; p <= last; p++) { for (int i = 0; i < separatorLength; i++) { if (toSplit.charAt(i + p) != separator.charAt(i)) { continue positions; } } return p; } return -1; } // 上一次分隔符出现的位置 加上 分割字符串 的长度,因为“上一次分隔符出现的位置”是其串首部 @Override public int separatorEnd(int separatorPosition) { return separatorPosition + separator.length(); }
PS:这里的positions是Java Label的用法,参考Java:标号label
到这里,这个策略模式就明了。
其余的点:
- omitEmptyStrings()方法如何配置Splitter实例分割后不包含empty子串
- limit()方法配置Splitter实例限制子串的数量
- trimResults()配置Splitter实例对得到的子串进行trim
- Iterable<String> split(final CharSequence sequence)方法进行正式分隔
- List<String> splitToList(CharSequence sequence)分割得到String List
等实现都比较好理解,不记录了。
策略模式小结
策略模式(Strategy)定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法的变化不会影响到使用算法的客户。