欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-04-22 20:22:27
...

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("")));
    }
}