文海沙龙想法简友广场

JAVA字符串常用方法

2019-07-21  本文已影响196人  binyulan517

JAVA字符串常用方法

  1. 截取字符串

    "hello".substring(1, 3); // el
    "hello".charAt(0); // h
    
    /** 
     * "𝕆" 占用了两个代码单元,即4字节 
     * charAt返回的是代码单元,所以返回的是一个不可见字符
     */
    "𝕆".charAt(0); // ?
    
  2. 使用分隔符合并字符串

    String[] strs = new String[]{"1", "2", "3"};
    String.join("|", strs)); // 1|2|3
    
  3. 判断字符串是否相等

    "hello".equals("Hello"); // false
    "hello".equalsIgnoreCase("Hello"); // true
    
  4. 按字典顺序比较字符串大小

    "a".compareTo("b"); // -1
    "b".compareTo("b"); // 0
    "b".compareTo("a"); // 1
    
  5. 判断以什么开头和结束

    "hello".startsWith("hel"); // true
    "hello".endsWith("ll"); // false
    
  6. 获取在字符串中的位置信息

    "hello".indexOf("l"); // 2
    "hello".lastIndexOf("l"); // 3
    
  7. 获取字符串长度

    "𝕆".length(); // 2
    "𝕆".codePointCount(0, "𝕆".length()); // 1
    
  8. 大小写转换

    "hello".toUpperCase(); // HELLO
    "HELLO".toLowerCase(); // hello
    
  9. 去除头尾空格

    "  h ello  ".trim(); // h ello
    
  10. 是否包含字符在内

    "hello".contains("e"); // true
    "hello".contains(""); // true
    "hello".contains(null) // throw NullPointerException
    
  11. String格式化format

    /**
     * %1$6s: 1$表示第一个参数,6表示第一个参数占6个位,不足6位左边补空格,s表示格式化成字符串
     * %1$S: 1$表示第一个参数,S表示格式成大写的字母
     */
    String.format("hello%1$6s %1$S", "world"); // hello world WORLD
    
  1. org.springframework.util.StringUtils工具类使用
StringUtils.isEmpty(""); // true; 判断字符串是否是""或者null
StringUtils.hasText("  "); // false; !isEmpty() 并且字符串不能全是空白字符
StringUtils.containsWhitespace("\t"); // true; 判断是否包含空白字符
StringUtils.trimWhitespace(" aa bb cc "); // "aa bb cc"; 同 String.trim();
StringUtils.trimArrayElements(new String[]{" aa ", " bb "}); // {"aa", "bb"}
StringUtils.trimAllWhitespace(" aa bb cc "); // "aabbcc"; 去掉所有的空白
StringUtils.trimLeadingWhitespace(" aa bb cc "); // "aa bb cc "; 头部空白
StringUtils.trimTrailingWhitespace(" aa bb cc "); // " aa bb cc"; 去尾部空白
StringUtils.trimLeadingCharacter(",hello", ','); // hello; 去除头部字符
StringUtils.trimTrailingCharacter("hello,", ','); // hello; 去除尾部字符
StringUtils.quote("hello"); // 'hello'; 单引号括起来字符串
StringUtils.capitalize("hello"); // Hello; 首字母变大写
StringUtils.uncapitalize("Hello"); // hello; 首字母变小写
StringUtils.uriDecode("http://www.auuid.com/%2B", Charset.forName("UTF-8")); // http://www.auuid.com/+; URI解码
上一篇 下一篇

猜你喜欢

热点阅读