Java字符串

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数组转为以逗号分隔的字符串

package net.test.common.util;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * sql操作工具类
 *
 */
public class SqlUtil
{
    /**
     * 仅支持字母、数字、下划线、空格、逗号(支持多个字段排序)
     */
    public static String SQL_PATTERN = "[a-zA-Z0-9_\\ \\,]+";
    
    /**
     * 将数组转换成以逗号分隔的字符串,拼成in格式
     *
     * @param strList 需要转换的数组
     * @return 以逗号分割的字符串
     */
    public static String joinWithComma(List<String> strList) {
        List<String> arr = new ArrayList<>();
        for (String str : strList) {
            String comma = "'" + str.trim() + "'";
            if (!arr.contains(comma) && StringUtils.isNotEmpty(str)) {
                arr.add(comma);
            }
        }
        return StringUtils.join(arr, ",");
    }
    
    /**
     * 检查字符,防止注入绕过
     */
    public static String escapeOrderBySql(String value)
    {
        if (StringUtils.isNotEmpty(value) && !isValidOrderBySql(value))
        {
            return StringUtils.EMPTY;
        }
        return value;
    }

    /**
     * 验证 order by 语法是否符合规范
     */
    public static boolean isValidOrderBySql(String value)
    {
        return value.matches(SQL_PATTERN);
    }
}

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包

commons-lang是Apache Commons 团队发布的工具包,相当于java.lang的增强版,commons-lang3要求jdk版本在1.5以上,相对于commons-lang来说完全支持java5的特性,废除了一些旧的API。该版本无法兼容旧有版本,于是为了避免冲突改名为lang3原来的 commons-lang 已停止更新。

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

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

查找

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.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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值