Strings 工具类
String 或 CharSequence 实例有关的静态实用程序方法。
一、类声明
以下是 com.google.common.base.Strings 类的声明:
@GwtCompatible public final class Strings extends Object
二、类方法
官方文档:https://google.github.io/guava/releases/27.0.1-jre/api/docs/com/google/common/base/Strings.html
| 修饰符和类型 | 方法说明 |
|---|---|
static String | commonPrefix(CharSequence a, CharSequence b) 返回共同的前缀字符串. |
static String | commonSuffix(CharSequence a, CharSequence b) 返回共同的后缀字符串. |
static @Nullable String | emptyToNull(@Nullable String string) 返回字符串非空字符串,返回原字符串。否则,返回null. |
static boolean | isNullOrEmpty(@Nullable String string) 判断字符串是不是null或者空字符串. |
static String | lenientFormat(@Nullable String template, Object... args) 返回给定的模板字符串,每次出现的“%s”都替换为args中对应的参数值; 或者,如果占位符和参数计数不匹配,则返回该字符串形式. |
static String | nullToEmpty(@Nullable String string) 返回字符串非null,返回原字符串。否则返回空字符串. |
static String | padEnd(String string, int minLength, char padChar) 返回字符串,长度最少是minLength,长度不够的话用重复的padChar填充. |
static String | padStart(String string, int minLength, char padChar) 返回字符串,长度最少是minLength,长度不够的话用重复的padChar填充. |
static String | repeat(String string, int count) 返回string重复count次. |
三、测试类
package com.example.guava.string_utilities;
import com.google.common.base.Strings;
import org.junit.Test;
/**
* Strings 工具
*/
public class StringsTest {
/**
* 1、如果为空或null 就返回 null
* 2、不为空或null 返回当前值
*/
@Test
public void test1() {
System.out.println(Strings.emptyToNull("")); // null
System.out.println(Strings.emptyToNull(null)); // null
System.out.println(Strings.emptyToNull(" "));
System.out.println(Strings.emptyToNull("hello world")); // hello world
}
/**
* 空值判断
*/
@Test
public void test2() {
System.out.println(Strings.isNullOrEmpty("")); // true
System.out.println(Strings.isNullOrEmpty(" ")); // false
System.out.println(Strings.isNullOrEmpty(null)); // true
}
/**
* 前缀、后缀
*/
@Test
public void test3() {
System.out.println(Strings.commonPrefix("Hello","Hit")); // D
System.out.println(Strings.commonPrefix("Hello","Xit")); // 空
System.out.println(Strings.commonSuffix("world","xid")); // d
System.out.println(Strings.commonSuffix("world","xic")); // 空
}
/**
* 重复数据
*/
@Test
public void test4() {
System.out.println(Strings.repeat("TingFeng",3)); // TingFengTingFengTingFeng
}
/**
* 数据填充
*
* 1、设定长度小于等于字符串长度 - 忽略
* 2、设定长度大于字符串长度忽略 - 填充
*/
@Test
public void test5() {
// 向前填充
System.out.println(Strings.padStart("Hello",3,'X')); // Hello
System.out.println(Strings.padStart("Hello",8,'X')); // XXXHello
// 向后填充
System.out.println(Strings.padEnd("Hello",3,'X')); // Hello
System.out.println(Strings.padEnd("Hello",8,'X')); // HelloXXX
}
}四、相关文章
未经允许请勿转载:程序喵 » Google Guava 快速入门 —— 【字符串处理】Strings 字符串处理
程序喵