String

216 阅读3分钟

String详解

1. 内置常用方法

  1. length()

    解释:获取字符串长度

  2. isEmpty()

    解释:仅支持判断长度为0

    /**
    * 仅支持判断长度为0,不支持判断对象为null
    **/
    public boolean isEmpty() {
        return value.length == 0;
    }
    

改进方案:建议使用org.apache.commons.lang3.StringUtils.isEmpty()方法

  1. indexOf(String str)

    解释:返回此字符串中指定字符第一次出现的索引。

  2. lastIndexOf(String str)

    解释:返回此字符串中指定子字符串最后一次出现的索引。

###5. subString(int beginIndex)

解释:返回作为此字符串的子字符串的字符串。子字符串以指定索引处的字符开始,并延伸到此字符串的末尾。

Examples:
       "unhappy".substring(2) returns "happy"
       "Harbison".substring(3) returns "bison"
       "emptiness".substring(9) returns "" (an empty string)
  1. replace(CharSequence target,CharSequence replacement)

    解释:将此字符串中与文字目标序列匹配的每个子字符串替换为指定的文字替换序列。替换从字符串的开头一直进行到结尾,例如,将字符串“aaa”中的“aa”替换为“b”将导致“ba”而不是“ab”。

  2. replaceFirst(String regex,String replacement)

    解释:用给定的替换项替换此字符串中与给定正则表达式匹配的第一个子字符串。

  3. replaceAll(String regex,String replacement)

    解释:用给定的替换项替换此字符串中与给定正则表达式匹配的每个子字符串。

  4. split(String regex,int limit)

    解释:围绕给定正则表达式的匹配项拆分此字符串。此方法返回的数组包含此字符串的每个子字符串,这些子字符串由与给定表达式匹配的另一个子字符串终止或由字符串末尾终止。

The string "boo:and:foo", for example, yields the following results with these parameters:
Regex     Limit     Result
  :         2       { "boo", "and:foo" }
  :         5       { "boo", "and", "foo" }
  :        -2       { "boo", "and", "foo" }
  o         5       { "b", "", ":and:f", "", "" }
  o        -2       { "b", "", ":and:f", "", "" }
  o         0       { "b", "", ":and:f" }
  1. split(String regex)

    解释:围绕给定正则表达式的匹配项拆分此字符串。此方法的工作方式就像是使用给定的表达式和零的极限参数调用双参数split方法一样。因此,尾随的空字符串不包括在结果数组中。

The string "boo:and:foo", for example, yields the following results with these expressions:
Regex     Result
  :       { "boo", "and", "foo" }
  o       { "b", "", ":and:f" }
  1. join(CharSequence delimiter, CharSequence... elements)

    解释:返回一个新的字符串,该字符串由CharSequence元素的副本与指定分隔符的副本连接在一起组成。

  2. join(CharSequence delimiter,Iterable<? extends CharSequence> elements)

    解释:返回一个新的字符串,该字符串由CharSequence元素的副本与指定分隔符的副本连接在一起组成。

  3. toLowerCase()

    解释:使用默认区域设置的规则将此字符串中的所有字符转换为小写。这相当于调用toLowerCase(Locale.getDefault())。

  4. toUpperCase()

    解释:使用默认区域设置的规则将此字符串中的所有字符转换为大写。这相当于调用toUpperCase(Locale.getDefault())。

  5. trim()

    解释:去除字符串首尾空字符串。

        public String trim() {
            int len = value.length;
            int st = 0;
            char[] val = value;    /* avoid getfield opcode */
    
            while ((st < len) && (val[st] <= ' ')) {
                st++;
            }
            while ((st < len) && (val[len - 1] <= ' ')) {
                len--;
            }
            return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
        }
    
  6. intern()

    解释: 将字符串对象添加到字符串常量池中,并返回该字符串在常量池中的引用。

  7. contains(CharSequence s)

    解释:是否包含该字符串

  8. matches(String regex)

    解释:告诉此字符串是否与给定的正则表达式匹配。

  9. format()

    解释:使用指定的区域设置、格式字符串和参数返回格式化字符串。

    public class StringFormatExample {
        public static void main(String[] args) {
            // 定义一些变量
            String name = "John";
            int age = 25;
            double height = 5.8;
    
            // 使用 String.format() 格式化字符串
            String formattedString = String.format("Name: %s, Age: %d, Height: %.2f", name, age, height);
    
            // 输出格式化后的字符串
            System.out.println(formattedString);
        }
    }
    

    2. 其他用法

    1. 将数字转化为中文

      /**
      * hutool convert
      * 格式化-999~999之间的数字<br>
      * 这个方法显示10~19以下的数字时使用"十一"而非"一十一"。
      *
      * @param amount           数字
      * @param isUseTraditional 是否使用繁体
      * @return 中文
      * @since 5.7.17
      */
      NumberChineseFormatter.formatThousand(int amount, boolean isUseTraditional)