Guava——Strings与CharMatcher

1. Strings

1.1 空字符串转null

String res1 = Strings.emptyToNull("");
System.out.println(res1 == null);

1.2 null转空字符串

String res2 = Strings.nullToEmpty(null);
System.out.println("".equals(res2));

1.3 判断对象是否为null或者空字符串

boolean nullOrEmpty = Strings.isNullOrEmpty("");
System.out.println("nullOrEmpty = " + nullOrEmpty);

1.4 循环拼接字符串

String res3 = Strings.repeat("Hello", 3);
System.out.println("res3 = " + res3);

1.5 获取2个字符串共有的前缀

String prefix = Strings.commonPrefix("google", "golang");
System.out.println("prefix = " + prefix);

1.6 获取2个字符串共有的后缀

String suffix = Strings.commonSuffix("guava", "viva");
System.out.println("suffix = " + suffix);

1.7 从前补齐字符串

String padStart = Strings.padStart("android", 10, '_');
System.out.println("padStart = " + padStart);

1.8 从后补齐字符串

String padEnd = Strings.padEnd("android", 10, '_');
System.out.println("padEnd = " + padEnd);

2. CharMatcher

2.1 布尔表达式

  • 等于 is
CharMatcher matcher = CharMatcher.is(',').or(CharMatcher.is('|')).or(CharMatcher.is('\t'));
boolean b = matcher.matches('|');
System.out.println("b = " + b);
  • 或者 or
CharMatcher orMatcher = CharMatcher.is(',').or(CharMatcher.is('\t'));
System.out.println("or = " + orMatcher.matches(','));
  • 并且 and
CharMatcher andMatcher = CharMatcher.inRange('a', 'd').and(CharMatcher.inRange('b', 'h'));
System.out.println("or = " + andMatcher.matches('c'));

2.2 字符比较

注: 此处以JAVA_DIGIT(数字)举例,其他依次类推

  • 比较字符是否是数字
boolean matches = CharMatcher.JAVA_DIGIT.matches('5');
System.out.println("matches = " + matches);
  • 获取是数字的字符的个数
int count = CharMatcher.JAVA_DIGIT.countIn("a3de8ss21d3");
System.out.println("count = " + count);
  • 去除前后的数字
String trim = CharMatcher.JAVA_DIGIT.trimFrom("111google222");
System.out.println("trim = " + trim);
  • 移除所有数字
String remove = CharMatcher.JAVA_DIGIT.removeFrom("111go1o3g4le222");
System.out.println("remove = " + remove);
  • 替换所有数字
String replace = CharMatcher.JAVA_DIGIT.replaceFrom("111go1o3g4le222", "|");
System.out.println("replace = " + replace);

2.3 获取角标

注: 此处以JAVA_DIGIT(数字)举例,其他依次类推

  • 获取第一个数字的角标
int index = CharMatcher.JAVA_DIGIT.indexIn("goo3g2le");
System.out.println("index = " + index);
  • 获取最后一个数字的角标
int index1 = CharMatcher.JAVA_DIGIT.lastIndexIn("goo3g2le");
System.out.println("index1 = " + index1);
  • 获取从某个位置开始的第一个数字的角标
int index2 = CharMatcher.JAVA_DIGIT.indexIn("goo3g2l2e", 4);
System.out.println("index2 = " + index2);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值