Java字符串

String[]转list

String[] array = {"a","b","c"};
List<String> list = Arrays.asList(array);

String[]去重复

String[] strings = {"apple", "banana", "apple", "orange", "banana"};
String[] uniqueStrings = Arrays.stream(strings).distinct().toArray(String[]::new);

按照字节截取字符串

  /**
   * 按照字节截取字符串
   *
   * @param src
   * @param byteType
   * @param bytes
   * @return
   */
  public static List<String> substringByte(String src, String byteType, int bytes) {
    if (StringUtils.isBlank(src)) {
      return Collections.EMPTY_LIST;
    }

    List<String> splitList = new ArrayList<String>();
    //字符串截取起始位置
    int startIndex = 0;
    //字符串截取结束位置
    int endIndex = bytes > src.length() ? src.length() : bytes;
    try {
      while (startIndex < src.length()) {
        //截取的字符串的字节长度大于需要截取的长度时,说明包含中文字符
        String subString = src.substring(startIndex, endIndex);
        //在GBK编码中,一个中文字符占2个字节,UTF-8编码格式,一个中文字符占3个字节。
        while (subString.getBytes(byteType).length > bytes) {
          --endIndex;
          subString = src.substring(startIndex, endIndex);
        }
        splitList.add(src.substring(startIndex, endIndex));
        startIndex = endIndex;
        //判断结束位置时要与字符串长度比较(src.length()),之前与字符串的bytes长度比较了,导致越界异常。
        endIndex = (startIndex + bytes) > src.length() ? src.length() : startIndex + bytes;
      }
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    return splitList;
  }

Java中驼峰与下划线相互转换

public class StringUtils extends org.apache.commons.lang3.StringUtils {

  /**
   * 下划线
   */
  private static final char SEPARATOR = '_';

  /**
   * 下划线转驼峰命名
   */
  public static String toUnderScoreCase(String str) {
    if (str == null) {
      return null;
    }
    StringBuilder sb = new StringBuilder();
    // 前置字符是否大写
    boolean preCharIsUpperCase = true;
    // 当前字符是否大写
    boolean curreCharIsUpperCase = true;
    // 下一字符是否大写
    boolean nexteCharIsUpperCase = true;
    for (int i = 0; i < str.length(); i++) {
      char c = str.charAt(i);
      if (i > 0) {
        preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1));
      } else {
        preCharIsUpperCase = false;
      }

      curreCharIsUpperCase = Character.isUpperCase(c);

      if (i < (str.length() - 1)) {
        nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1));
      }

      if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase) {
        sb.append(SEPARATOR);
      } else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase) {
        sb.append(SEPARATOR);
      }
      sb.append(Character.toLowerCase(c));
    }

    return sb.toString();
  }

  /**
   * 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。 例如:HELLO_WORLD->HelloWorld
   *
   * @param name 转换前的下划线大写方式命名的字符串
   * @return 转换后的驼峰式命名的字符串
   */
  public static String convertToCamelCase(String name) {
    StringBuilder result = new StringBuilder();
    // 快速检查
    if (name == null || name.isEmpty()) {
      // 没必要转换
      return "";
    } else if (!name.contains("_")) {
      // 不含下划线,仅将首字母大写
      return name.substring(0, 1).toUpperCase() + name.substring(1);
    }
    // 用下划线将原始字符串分割
    String[] camels = name.split("_");
    for (String camel : camels) {
      // 跳过原始字符串中开头、结尾的下换线或双重下划线
      if (camel.isEmpty()) {
        continue;
      }
      // 首字母大写
      result.append(camel.substring(0, 1).toUpperCase());
      result.append(camel.substring(1).toLowerCase());
    }
    return result.toString();
  }

  /**
   * 驼峰式命名法 例如:user_name->userName
   */
  public static String toCamelCase(String s) {
    if (s == null) {
      return null;
    }
    s = s.toLowerCase();
    StringBuilder sb = new StringBuilder(s.length());
    boolean upperCase = false;
    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);

      if (c == SEPARATOR) {
        upperCase = true;
      } else if (upperCase) {
        sb.append(Character.toUpperCase(c));
        upperCase = false;
      } else {
        sb.append(c);
      }
    }
    return sb.toString();
  }
}

StringUtils包

Lang3提供了许多Java库无法提供的辅助工具类,比如字符串,数值,反射,序列化等。如果熟练使用该包下的工具类,将节省我们的开发时间,避免重复实现,减少出错的可能。

com.baomidou.mybatisplus.toolkit.StringUtils包中主要:驼峰与下划线相互转换

<dependency>  
    <groupId>org.apache.commons</groupId>  
    <artifactId>commons-lang3</artifactId>  
    <version>3.12.0</version>  
</dependency>

常用的工具类与功能

  • 字符串相关操作 StringUtils
  • 数字相关操作 NumberUtils
  • 布尔相关操作 BooleanUtils
  • 反射相关操作 FieldUtils、MethodUtils、MemberUtils、TypeUtils、ConstructorUtils
  • 对象相关操作 ObjectUtils
  • 序列化相关操作 SerializationUtils

查找

StringUtils.startsWith("3100444", "31");
StringUtils.endsWith("3100444", "44");
StringUtils.endsWithIgnoreCase("3100444", "44");

StringUtils.contains("3100444", "00");
StringUtils.equals("3100444", "3100444");

大小写

字符串首字母大小写转换

StringUtils.capitalize(null)); // null (注意此处不会报异常)
StringUtils.capitalize("china")); // China (首字母转大写)
StringUtils.uncapitalize(null)); // null  
StringUtils.uncapitalize("CHINA")); // cHINA (首字母转小写)

判断字符串是否全部是大写或小写(空或空白符均为false)

StringUtils.isAllUpperCase(null)); // false
StringUtils.isAllUpperCase("")); // false
StringUtils.isAllUpperCase(" ")); // false
StringUtils.isAllUpperCase("CHINA")); // true
StringUtils.isAllLowerCase(null)); // false
StringUtils.isAllLowerCase("")); // false
StringUtils.isAllLowerCase(" ")); // false
StringUtils.isAllLowerCase("china")); // true

字符串大小写互换

StringUtils.swapCase(null)); // null
StringUtils.swapCase("chINA")); // CHina

字符串整体大小写转换

StringUtils.upperCase(null)); // null
StringUtils.upperCase("china")); // CHINA (全部转为大写)
StringUtils.upperCase("china", Locale.ENGLISH)); // CHINA (按照指定规则转换为大写)
StringUtils.lowerCase(null)); // null
StringUtils.lowerCase("CHINA")); // china (全部转换为小写)
StringUtils.lowerCase("CHINA", Locale.ENGLISH)); // china (按照指定转换规则转换为小写)

去除字符串两边的字符串

StringUtils.strip("[abc]","[]") = abc

比较字符串

StringUtils.containsAny(null, *)            = false
StringUtils.containsAny("", *)              = false
StringUtils.containsAny(*, null)            = false
StringUtils.containsAny(*, "")              = false
StringUtils.containsAny("zzabyycdxx", "za") = true
StringUtils.containsAny("zzabyycdxx", "by") = true
StringUtils.containsAny("aba","z")          = false
StringUtils.contains(null, *)     = false
StringUtils.contains(*, null)     = false
StringUtils.contains("", "")      = true
StringUtils.contains("abc", "")   = true
StringUtils.containsIgnoreCase("Abc", "a")  = true
StringUtils.contains("abc", "z")  = false

StringUtils.containsAny("abcxyz", new String[] {null, "xyz", "abc"})

移除空白字符

StringUtils.deleteWhitespace(null)); //null
StringUtils.deleteWhitespace(" c h  i\tn\ra")); // china

删除左边指定的长度字符串

 StringUtils.substring("02787976545", 3);

删除指定字符串

//删除指定字符、字符串
StringUtils.remove("queued", "u") = "qeed"
StringUtils.remove("queued", "zz") = "queued"
//删除字符串开始匹配的指定字符串  
StringUtils.removeStart("www.domain.com", "www.")  = "domain.com"
StringUtils.removeStart("domain.com", "www.") = "domain.com"
StringUtils.removeStart("www.domain.com", "domain") = "www.domain.com"
StringUtils.removeStart("abc", "") = "abc"
//删除字符串结尾匹配的指定字符串  
StringUtils.removeEnd("www.domain.com", ".com.")  = "www.domain.com"
StringUtils.removeEnd("www.domain.com", ".com")   = "www.domain"
StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com"
StringUtils.removeEnd("abc", "")  = "abc"
///删除字符串开始匹配的指定字符串,忽略大小写
StringUtils.removeStartIgnoreCase("www.domain.com", "www.")   = "domain.com"
StringUtils.removeStartIgnoreCase("www.domain.com", "WWW.")   = "domain.com"
StringUtils.removeStartIgnoreCase("domain.com", "www.")       = "domain.com"
StringUtils.removeStartIgnoreCase("www.domain.com", "domain") = "www.domain.com"
StringUtils.removeStartIgnoreCase("abc", "") = "abc"
//删除字符串结尾匹配的指定字符串,忽略大小写
StringUtils.removeEndIgnoreCase("www.domain.com", ".com.")  = "www.domain.com"
StringUtils.removeEndIgnoreCase("www.domain.com", ".com")   = "www.domain"
StringUtils.removeEndIgnoreCase("www.domain.com", "domain") = "www.domain.com"
StringUtils.removeEndIgnoreCase("abc", "")    = "abc"
StringUtils.removeEndIgnoreCase("www.domain.com", ".COM") = "www.domain")
StringUtils.removeEndIgnoreCase("www.domain.COM", ".com") = "www.domain")

替换

替换单个字符序列

StringUtils.replace("china", null, "z")); // china (此处被替换字符序列为null,因此替换会被忽略,返回原字符串)
StringUtils.replace("china", "c", null)); // china (此处替换字符序列为null,因此替换也被忽略,返回原字符串)
StringUtils.replace("china", "a", "ese")); // chinese
StringUtils.replace("china", "a", "")); // chin

StringUtils.replaceIgnoreCase(null, *, *)        = null 
StringUtils.replaceIgnoreCase("", *, *)          = "" 
StringUtils.replaceIgnoreCase("any", null, *)    = "any" 
StringUtils.replaceIgnoreCase("any", *, null)    = "any" 
StringUtils.replaceIgnoreCase("any", "", *)      = "any" 
StringUtils.replaceIgnoreCase("aba", "a", null)  = "aba" 
StringUtils.replaceIgnoreCase("abA", "A", "")    = "b" 
StringUtils.replaceIgnoreCase("aba", "A", "z")   = "zbz"

StringUtils.replaceEach("userName As user_name", new String[]{"As", "aS", "AS"}, new String[]{"as", "as", "as"});

替换。起始索引start小于结束索引end,这时会将end作为起始索引,start作为结束索引

StringUtils.overlay("abcdef", "zzzz", 4, 2)); // abzzzzef
StringUtils.overlay("abcdef", "zzzz", 4, 3)); // abczzzzef
StringUtils.overlay("abcdef", "zzzz", 4, 4)); // abcdzzzzef
StringUtils.overlay("abcdef", "zzzz", 4, 5)); // abcdzzzzf

反转

简单反转

StringUtils.reverse("china")); // anihc

根据指定分隔符进行反转,分隔符之间的字符不进行反转

StringUtils.reverseDelimited("china", ',')); // china
StringUtils.reverseDelimited("cxhinxa", 'x')); // axhinxz
StringUtils.reverseDelimited("c.hin.a", '.')); // a.hin.c
StringUtils.reverseDelimited("c.hina", '.')); // hina.c

截取字符串

//从左边开始截取指定个数
System.out.println(StringUtils.left("adsdfas", 2));//ad
//从右边开始截取指定个数
System.out.println(StringUtils.right("adsdfas", 2));//as
//从中间的指定位置开始截取  指定个数
System.out.println(StringUtils.mid("adsdfas", 2,2));//sd

StringUtils.truncate("12345",2,3) = 345

截取指定长度之后的字符

StringUtils.substring("684603104991682", 4)

字符串补齐 

StringUtils.leftPad("oldStr2", 10, "*"); //***oldStr2

StringUtils.rightPad(null, *, *)     ;// null
StringUtils.rightPad("", 3, 'z')    ;// "zzz"
StringUtils.rightPad("bat", 3, 'z') ;// "bat"
StringUtils.rightPad("bat", 5, 'z') ;// "batzz"
StringUtils.rightPad("bat", 1, 'z') ;// "bat"
StringUtils.rightPad("bat", -1, 'z');// "bat

isAlpha判断字符串是否全由字母组成 (只要存在汉字、中文、数字都为false)

StringUtils.isAlpha(null)  ;// false
 StringUtils.isAlpha("")    ;// false
 StringUtils.isAlpha("  ")   ;// false
 StringUtils.isAlpha("abc")  ;// true
 StringUtils.isAlpha("ab2c") ;// false
 StringUtils.isAlpha("ab-c") ;//false

提取字符串中数值部分

StringUtils.getDigits("abc123def456") = 123456

如果字符串为空,则用默认字符串代替

StringUtils.defaultIfEmpty(null,"123") = 123
StringUtils.defaultIfEmpty("","123") = 123

字符串是否是空白

StringUtils.isWhitespace(null) = false
StringUtils.isWhitespace("") = true
StringUtils.isWhitespace(" ") = true
StringUtils.isWhitespace("abc") =false

isNotBlank 与 isNotEmpty 区别

  • StringUtils.isNotEmpty:只检查字符串是否为空(长度为0),不关心字符串是否只包含空白字符。
  • StringUtils.isNotBlank:除了检查字符串是否为空外,还检查字符串是否只包含空白字符(换行、空格、制表符等)。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值