字符串处理之Splitter和Joiner
2017-08-21 本文已影响0人
千释炎
在google guava包中提供了用于字符串连接(Joiner)和字符串分割(Splitter)的类
Joiner
主要方法有:
/**
*返回一个在连续元素之间自动放置分隔符(separator)的joiner
*Returns a joiner which automatically places {@code separator} between consecutive
*elements.
*/
public static Joiner on(String separator) {
return new Joiner(separator);
}
//该方法同上
public static Joiner on(char separator) {
return new Joiner(String.valueOf(separator));
}
//构造方法用private修饰,不允许外部类直接用new创建
private Joiner(String separator) {
//separator不能为null,否则将抛出空指针异常
this.separator = checkNotNull(separator);
}
private Joiner(Joiner prototype) {
this.separator = prototype.separator;
}
/**
*返回一个用分隔符将Iterable中每一个参数进行分离后的结果,例子见后面
*Returns a string containing the string representation of each of {@code parts}, using
*the previously configured separator between each.
*/
public final String join(Iterable<?> parts) {
return join(parts.iterator());
}
同样的,对于数组有:
public final String join(Object[] parts) {
return join(Arrays.asList(parts));
}
还提供了skipNulls()方法和useForNull()方法对空元素进行处理
example:
import com.google.common.base.Joiner;
public class Demo {
public static void main(String args[]) {
Joiner joiner=Joiner.on(";");
String result=joiner.join("whisper","godyan","yan");
System.out.println(result);
}
}
输出:
whisper;godyan;yan
默认情况下,元素不能包含null,否则将抛出空指针异常,例如
joiner.join("whisper","godyan",null,"yan")
当参数中的元素包含null时,可通过skipNulls()和useForNull()方法将null排除
example:
import com.google.common.base.Joiner;
public class Demo {
public static void main(String args[]) {
Joiner joiner=Joiner.on(";").skipNulls();
//或Joiner joiner=Joiner.on(";").useForNull();
String result=joiner.join("whisper","godyan",null,"yan");
System.out.println(result);
}
}
输出:
whisper;godyan;yan
Splitter
主要方法有:
//返回使用给定的单字符分隔符的拆分器
/**
*Returns a splitter that uses the given single-character separator. For example,
*{@code Splitter.on(',').split("foo,,bar")} returns an iterable containing
*{@code ["foo", "", "bar"]}.
*@param separator the character to recognize as a separator
*@return a splitter, with default settings, that recognizes that separator
*/
public static Splitter on(char separator) {
return on(CharMatcher.is(separator));
}
//返回一个将字符串分割为给定长度部分的分割器
public static Splitter fixedLength(final int length) {
checkArgument(length > 0, "The length may not be less than 1");
return new Splitter(
new Strategy() {
@Override
public SplittingIterator iterator(final Splitter splitter, CharSequence toSplit) {
return new SplittingIterator(splitter, toSplit) {
@Override
public int separatorStart(int start) {
int nextChunkStart = start + length;
return (nextChunkStart < toSplit.length() ? nextChunkStart : -1);
}
@Override
public int separatorEnd(int separatorPosition) {
return separatorPosition;
}
};
}
});
}
//指定将字符串分割为limit部分
public Splitter limit(int limit) {
checkArgument(limit > 0, "must be greater than zero: %s", limit);
return new Splitter(strategy, omitEmptyStrings, trimmer, limit);
}
//调用该方法将自动移除元素首尾的空格
public Splitter trimResults() {
return trimResults(CharMatcher.whitespace());
}
//与上述方法不同的是,该方法可以将每个元素中所有头部或者所有尾部指定字符移除,具体见例子
public Splitter trimResults(CharMatcher trimmer) {
checkNotNull(trimmer);
return new Splitter(strategy, omitEmptyStrings, trimmer, limit);
}
//返回一个用指定分隔符对参数(sequence)进行分割后生成的Iterable对象
/**
*Splits {@code sequence} into string components and makes them available through
*an {@link Iterator}, which may be lazily evaluated. If you want an eagerly computed
*{@link List}, use {@link #splitToList(CharSequence)}.
*@param sequence the sequence of characters to split
*@return an iteration over the segments split from the parameter.
*/
public Iterable<String> split(final CharSequence sequence) {
checkNotNull(sequence);
return new Iterable<String>() {
@Override
public Iterator<String> iterator() {
return splittingIterator(sequence);
}
@Override
public String toString() {
return Joiner.on(", ")
.appendTo(new StringBuilder().append('['), this)
.append(']')
.toString();
}
};
}
//使用该方法可以自动省略空字符串
public Splitter omitEmptyStrings() {
return new Splitter(strategy, true, trimmer, limit);
}
example:
import com.google.common.base.Splitter;
public class Demo {
public static void main(String args[]) {
Splitter splitter=Splitter.on(",");
Iterable<String> itr=splitter.split("whisper,godyan,yan");
for(String str:itr) {
System.out.print(str+"\t");
}
}
}
输出:
whisper godyan yan
example:
import com.google.common.base.Splitter;
public class Demo {
public static void main(String args[]) {
Splitter splitter=Splitter.on(",");
Iterable<String> itr=splitter.split("whisper,,,godyan,yan");
for(String str:itr) {
System.out.print(str+"\t");
}
}
}
输出:
whisper godyan yan
其中whisper和godyan之间包含两个空字符串
example:
import com.google.common.base.Splitter;
public class Demo {
public static void main(String args[]) {
Splitter splitter=Splitter.on(",")..trimResults();
//,和yan之间的空格将自动移除
//Splitter splitter=Splitter.on(",")..trimResults(CharMatcher.is('_')).split("_a ,_b_ ,c__")将a中头部的_移除,b中头部_移除,c中尾部__移除,所以分割后的元素为a,b_,c,注意b后面的_没有移除
Iterable<String> itr=splitter.split("whisper,,,godyan, yan");
for(String str:itr) {
System.out.print(str+"\t");
}
}
}
注意:
如果要去掉null元素,这种写法是错的,skipNull()方法将不起作用
Joiner joiner = Joiner.on(',');
joiner.skipNulls();
return joiner.join("wrong", null, "wrong");}
同样的,像Splitter这种方法也是错误的,trimResults()方法也不起作用
Splitter splitter = Splitter.on('/');
splitter.trimResults();
return splitter.split("wrong / wrong / wrong");}