02-guava CharMatcher、Charsets、Strings

CharMatcher

1
2
3
4
5
6
7
8
try{
byte[] bytes = "foobarbaz".getBytes("UTF-8");
}catch (UnsupportedEncodingException e){
//This really can't happen UTF-8 must be supported
}

简写:
byte[] bytes2 = "foobarbaz".getBytes(Charsets.UTF_8);

Strings

Strings类为使用字符串提供了一些方便的实用方法。

  • 字符填充

    1
    2
    Strings.padEnd("foo", 6, 'x');//fooxxx
    Strings.padEnd("fooaaa", 6, 'x');//fooaaa
  • 空处理

nullToEmpty:这个方法接受一个字符串作为参数并返回
如果值不为空或长度大于0,则为原始字符串;否则
它返回空串

emptyToNull:该方法以类似于nullToEmpty的方式执行,
但如果字符串参数为空或者为null,则返回null

isNullOrEmpty:此方法对字符串执行空长检查
,如果该字符串实际上为null或空(长度为0),则返回true

CharMatcher

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@Test
public void testRemoveWhiteSpace(){
String tabsAndSpaces = "String with spaces and
tabs";
String expected = "String with spaces and tabs";
String scrubbed = CharMatcher.WHITESPACE.
collapseFrom(tabsAndSpaces,' ');
assertThat(scrubbed,is(expected));
}

@Test
public void testTrimRemoveWhiteSpace(){
String tabsAndSpaces = " String with spaces and
tabs";
String expected = "String with spaces and tabs";
String scrubbed = CharMatcher.WHITESPACE.
trimAndCollapseFrom(tabsAndSpaces,' ');
assertThat(scrubbed,is(expected));
}

@Test
public void testRetainForm() {
String letterAndNumbers = "foo989yxbar234";
String expected = "989234";
String retained = CharMatcher.JAVA_DIGIT.retainFrom(letterAndNumbers);
Assert.assertThat(expected, is(retained));
}

来源:Getting Started with Google Guava