Guava部分字符串处理工具类的例子

阅读更多

1.CaseFormat

import com.google.common.base.CaseFormat;
import static com.le.test.Printer.*;

/**
 *
 * @author zhongchenghui
 */
public class CaseFormatTest {

    public static void main(String[] args) {
        println(CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, "areaCode"));// returns "constantName"
        println(CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_UNDERSCORE, "area-code"));// returns "constantName"
        println(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "area_code"));// returns "constantName"
        println(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_CAMEL, "AreaCode"));// returns "constantName"
        println(CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_UNDERSCORE, "AREA_CODE"));// returns "constantName"
    }
}

public class Printer {

    public static void println(Object object) {
        System.out.println(object);
    }
}

 2.CharMatcher

import com.google.common.base.CharMatcher;
import static com.le.test.Printer.*;

/**
 *
 * @author zhongchenghui
 */
public class CharMatcherTest {

    public static void main(String[] args) {
        String string = " sf4s  dfI54YOd        IUYIU   234jlklsf23 ";
        //移除control字符
        println(CharMatcher.JAVA_LOWER_CASE.removeFrom(string));
        //只保留数字字符
        println(CharMatcher.DIGIT.retainFrom(string));
        //去除两端的空格,并把中间的连续空格替换成单个空格
        println(CharMatcher.WHITESPACE.trimAndCollapseFrom(string, ' '));
        //用*号替换所有数字
        println(CharMatcher.JAVA_DIGIT.replaceFrom(string, "*"));
        // 只保留数字和小写字母
        println(CharMatcher.JAVA_DIGIT.or(CharMatcher.JAVA_LOWER_CASE).retainFrom(string));
    }
}

 3.Joiner

import com.google.common.base.Joiner;
import static com.le.test.Printer.*;
import java.util.Arrays;

/**
 *
 * @author zhongchenghui
 */
public class JoinerTest {

    public static void main(String[] args) {
        println(Joiner.on(";").skipNulls().join("Harry", null, "Ron", "Hermione"));
        println(Joiner.on(";").useForNull("Tic").join("Harry", null, "Ron", "Hermione"));
        println(Joiner.on(",").join(Arrays.asList(1, 5, 7))); // returns "1,5,7"
    }
}

 4.Splitter

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import static com.le.test.Printer.*;

/**
 *
 * @author zhongchenghui
 */
public class SplitterTest {

    public static void main(String[] args) {

        println(Lists.newArrayList(Splitter.on("##").trimResults().omitEmptyStrings().split("a##b##")));
        println(Lists.newArrayList(Splitter.on("##").trimResults().omitEmptyStrings().split(" a ##b ## ")));
        println(Lists.newArrayList(Splitter.on("##").trimResults().omitEmptyStrings().split(" a ###b #c# d##")));
        println(Lists.newArrayList(Splitter.on("##").trimResults().omitEmptyStrings().split("")));
    }
}

 

 

你可能感兴趣的:(guava,字符串,工具类)