字符串处理相关

字符串处理相关

一、String

(一)完整列表

详细列出了 String 类的所有方法,包括常见和不常见的方法。从功能性方法到继承自 Object 类的基本方法已经涵盖。为了提供更全面的参考,下面是 String 类的方法的完整列表,确保没有遗漏:

String 类的方法列表(完整)

  1. charAt(int index)
  2. codePointAt(int index)
  3. codePointBefore(int index)
  4. codePointCount(int beginIndex, int endIndex)
  5. compareTo(String anotherString)
  6. compareToIgnoreCase(String str)
  7. concat(String str)
  8. contains(CharSequence s)
  9. contentEquals(CharSequence cs)
  10. contentEquals(StringBuffer sb)
  11. copyValueOf(char[] data)
  12. copyValueOf(char[] data, int offset, int count)
  13. endsWith(String suffix)
  14. equals(Object anObject)
  15. equalsIgnoreCase(String anotherString)
  16. format(Locale l, String format, Object… args)
  17. format(String format, Object… args)
  18. getBytes()
  19. getBytes(Charset charset)
  20. getBytes(String charsetName)
  21. getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin)
  22. getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
  23. hashCode()
  24. indexOf(int ch)
  25. indexOf(int ch, int fromIndex)
  26. indexOf(String str)
  27. indexOf(String str, int fromIndex)
  28. intern()
  29. isEmpty()
  30. lastIndexOf(int ch)
  31. lastIndexOf(int ch, int fromIndex)
  32. lastIndexOf(String str)
  33. lastIndexOf(String str, int fromIndex)
  34. length()
  35. matches(String regex)
  36. offsetByCodePoints(int index, int codePointOffset)
  37. regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
  38. regionMatches(int toffset, String other, int ooffset, int len)
  39. replace(char oldChar, char newChar)
  40. replace(CharSequence target, CharSequence replacement)
  41. replaceAll(String regex, String replacement)
  42. replaceFirst(String regex, String replacement)
  43. split(String regex)
  44. split(String regex, int limit)
  45. startsWith(String prefix)
  46. startsWith(String prefix, int toffset)
  47. subSequence(int beginIndex, int endIndex)
  48. substring(int beginIndex)
  49. substring(int beginIndex, int endIndex)
  50. toCharArray()
  51. toLowerCase()
  52. toLowerCase(Locale locale)
  53. toString()
  54. toUpperCase()
  55. toUpperCase(Locale locale)
  56. trim()
  57. valueOf(boolean b)
  58. valueOf(char c)
  59. valueOf(char[] data)
  60. valueOf(char[] data, int offset, int count)
  61. valueOf(double d)
  62. valueOf(float f)
  63. valueOf(int i)
  64. valueOf(long l)
  65. valueOf(Object obj)
  66. repeat(int count)
  67. strip()
  68. stripLeading()
  69. stripTrailing()
  70. isBlank()
  71. lines()
  72. chars()
  73. codePoints()
  74. indent(int n)
  75. transform(Function<String, R> f)
  76. describeConstable()
  77. resolveConstantDesc(Lookup lookup)

继承自 Object 类的方法:

  1. getClass()
  2. notify()
  3. notifyAll()
  4. wait()
  5. wait(long timeout)
  6. wait(long timeout, int nanos)

示例代码补充

为了帮助你更好地理解这些方法的使用,以下是一些示例代码:

import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class StringMethodsExampleFull {
    public static void main(String[] args) throws InterruptedException {
        // getBytes
        byte[] defaultBytes = "hello".getBytes();
        byte[] utf8Bytes = "hello".getBytes(StandardCharsets.UTF_8);
        byte[] specifiedBytes = "hello".getBytes("UTF-8");
        System.out.println("Default bytes: " + Arrays.toString(defaultBytes));
        System.out.println("UTF-8 bytes: " + Arrays.toString(utf8Bytes));
        System.out.println("Specified bytes: " + Arrays.toString(specifiedBytes));

        // getClass
        Class<? extends String> strClass = "hello".getClass();
        System.out.println("Class: " + strClass.getName());

        // notify, notifyAll, and wait
        // Note: These methods are generally used in multi-threading context.
        Object lock = new Object();
        synchronized (lock) {
            lock.notify();
            lock.notifyAll();
            lock.wait(1000);
            lock.wait(1000, 500);
        }

        // Other methods such as `hashCode`, `equals`, and `toString` are inherited from the Object class
        String str = "hello";
        int hashCode = str.hashCode();
        boolean equals = str.equals("hello");
        String toString = str.toString();
        System.out.println("Hash code: " + hashCode);
        System.out.println("Equals: " + equals);
        System.out.println("To string: " + toString);
    }
}

(二)对完整列表进行分类

为了进一步细化 String 类的方法,我将对每个方法的具体用途进行更详细的分类,并根据功能进行更多的子分类。这样你可以更准确地找到每个方法。

1. 创建和转换

1.1 从基本类型创建字符串
  • valueOf(boolean b): 将布尔值 truefalse 转换为字符串 "true""false"
  • valueOf(char c): 将单个字符转换为包含该字符的字符串。
  • valueOf(double d): 将双精度浮点数转换为其字符串表示形式。
  • valueOf(float f): 将单精度浮点数转换为其字符串表示形式。
  • valueOf(int i): 将整数转换为其字符串表示形式。
  • valueOf(long l): 将长整数转换为其字符串表示形式。
1.2 从对象和数组创建字符串
  • valueOf(Object obj): 将对象转换为其字符串表示形式(调用对象的 toString 方法)。如果对象为 null,则返回字符串 "null"
  • valueOf(char[] data): 将字符数组转换为字符串,包含数组中的所有字符。
  • valueOf(char[] data, int offset, int count): 将字符数组的一部分(从指定的偏移量开始的指定长度)转换为字符串。
1.3 字符数组转换
  • toCharArray(): 将字符串转换为一个新的字符数组,包含字符串中的所有字符。
1.4 字符串表示
  • toString(): 返回字符串本身,这通常是在对象被打印或连接时隐式调用的。

2. 比较和匹配

2.1 内容比较
  • equals(Object anObject): 比较两个字符串的内容是否完全相同,区分大小写。
  • equalsIgnoreCase(String anotherString): 比较两个字符串的内容是否相同,忽略大小写。
2.2 字典顺序比较
  • compareTo(String anotherString): 按字典顺序比较两个字符串。返回负整数、零或正整数,分别表示此字符串小于、等于或大于指定字符串。
  • compareToIgnoreCase(String str): 忽略大小写按字典顺序比较两个字符串。返回负整数、零或正整数,分别表示此字符串小于、等于或大于指定字符串。
2.3 内容相等性比较
  • contentEquals(CharSequence cs): 比较此字符串与指定的字符序列的内容是否相同。
  • contentEquals(StringBuffer sb): 比较此字符串与指定的 StringBuffer 的内容是否相同。
2.4 局部比较
  • regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len): 比较两个字符串的指定区域是否相同,可以选择忽略大小写。
  • regionMatches(int toffset, String other, int ooffset, int len): 比较两个字符串的指定区域是否完全相同,区分大小写。
2.5 前缀和后缀匹配
  • startsWith(String prefix): 判断字符串是否以指定前缀开头。
  • startsWith(String prefix, int toffset): 判断字符串从指定索引开始是否以指定前缀开头。
  • endsWith(String suffix): 判断字符串是否以指定后缀结尾。
2.6 正则表达式匹配
  • matches(String regex): 判断字符串是否匹配给定的正则表达式。

3. 搜索和查找

3.1 查找字符
  • indexOf(int ch): 返回指定字符在字符串中首次出现的索引,如果字符未出现则返回 -1
  • indexOf(int ch, int fromIndex): 从指定索引开始,返回指定字符在字符串中首次出现的索引,如果字符未出现则返回 -1
  • lastIndexOf(int ch): 返回指定字符在字符串中最后一次出现的索引,如果字符未出现则返回 -1
  • lastIndexOf(int ch, int fromIndex): 从指定索引开始向后搜索,返回指定字符在字符串中最后一次出现的索引,如果字符未出现则返回 -1
3.2 查找子字符串
  • indexOf(String str): 返回指定子字符串在字符串中首次出现的索引,如果子字符串未出现则返回 -1
  • indexOf(String str, int fromIndex): 从指定索引开始,返回指定子字符串在字符串中首次出现的索引,如果子字符串未出现则返回 -1
  • lastIndexOf(String str): 返回指定子字符串在字符串中最后一次出现的索引,如果子字符串未出现则返回 -1
  • lastIndexOf(String str, int fromIndex): 从指定索引开始向后搜索,返回指定子字符串在字符串中最后一次出现的索引,如果子字符串未出现则返回 -1
3.3 包含检查
  • contains(CharSequence s): 判断字符串是否包含指定的字符序列。

4. 修改和操作

4.1 字符串拼接
  • concat(String str): 连接两个字符串,将指定字符串连接到此字符串的末尾。
4.2 替换字符串内容
  • replace(char oldChar, char newChar): 替换字符串中所有出现的指定字符。
  • replace(CharSequence target, CharSequence replacement): 替换字符串中所有出现的指定字符序列。
  • replaceAll(String regex, String replacement): 使用正则表达式替换所有匹配的子字符串。
  • replaceFirst(String regex, String replacement): 使用正则表达式替换第一个匹配的子字符串。
4.3 提取子字符串
  • substring(int beginIndex): 从指定索引开始截取子字符串,直到字符串末尾。
  • substring(int beginIndex, int endIndex): 从指定索引范围内截取子字符串。
4.4 提取字符序列
  • subSequence(int beginIndex, int endIndex): 从指定索引范围内截取字符序列。
4.5 去除空白字符
  • trim(): 去除字符串首尾的空白字符。
  • strip(): 去除字符串首尾的空白字符,包括 Unicode 空白字符(Java 11 新增)。
  • stripLeading(): 去除字符串首部的空白字符,包括 Unicode 空白字符(Java 11 新增)。
  • stripTrailing(): 去除字符串尾部的空白字符,包括 Unicode 空白字符(Java 11 新增)。
4.6 重复字符串
  • repeat(int count): 重复指定次数并创建新字符串(Java 11 新增)。
4.7 缩进字符串
  • indent(int n): 缩进字符串若干空格,正值增加空格,负值减少空格(Java 12 新增)。
4.8 字符串变换
  • transform(Function<String, R> f): 将字符串应用给定的函数并返回结果(Java 12 新增)。

5. 信息和状态

5.1 长度和空状态检查
  • length(): 返回字符串的长度(字符数)。
  • isEmpty(): 判断字符串是否为空(长度为 0)。
  • isBlank(): 判断字符串是否为空白(仅包含空白字符)(Java 11 新增)。
5.2 哈希码
  • hashCode(): 返回字符串的哈希码,哈希码是基于字符串内容计算的。
5.3 类信息
  • getClass(): 返回字符串的类对象。

6. 字符和字节处理

6.1 获取字符和代码点
  • charAt(int index): 返回指定索引处的字符。
  • codePointAt(int index): 返回指定索引处的 Unicode 代码点。
  • codePointBefore(int index): 返回指定索引前一个位置的 Unicode 代码点。
  • codePointCount(int beginIndex, int endIndex): 返回指定索引范围内的 Unicode 代码点数量。
  • offsetByCodePoints(int index, int codePointOffset): 返回从指定索引按代码点偏移后的索引。
6.2 转换为字节数组
  • getBytes(): 以默认字符集编码返回字符串的字节数组。
  • getBytes(Charset charset): 以指定字符集编码返回字符串的字节数组。
  • getBytes(String charsetName): 以指定字符集名称编码返回字符串的字节数组。
  • getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin): 将指定索引范围内的字符转换为字节并存储到指定的字节数组中。
6.3 转换为字符数组
  • getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin): 将指定索引范围内的字符存储到字符数组中。

7. 流和迭代

7.1 创建字符流和代码点流
  • chars(): 返回字符串的字符流,每个元素是字符的整数表示。
  • codePoints(): 返回字符串的代码点流,每个元素是 Unicode 代码点的整数表示。
7.2 行流处理
  • lines(): 返回按行分隔的字符流(Java 11 新增)。

8. 线程和同步

  • notify(): 唤醒在此对象监视器上等待的单个线程。
  • notifyAll(): 唤醒在此对象监视器上等待的所有线程。
  • wait(): 使当前线程等待,直到其他线程在此对象上调用 notifynotifyAll 方法。
  • wait(long timeout): 使当前线程等待指定时间(毫秒),直到其他线程在此对象上调用 notifynotifyAll 方法。
  • wait(long timeout, int nanos): 使当前线程等待指定时间(毫秒和纳秒),直到其他线程在此对象上调用 notifynotifyAll 方法。

9. 高级和特殊

  • intern(): 返回字符串对象的规范化表示。它从常量池中返回字符串,保证相同字符序列的字符串只存在一个实例。
  • describeConstable(): 返回描述此字符串常量的 Optional 对象(Java 12 新增)。
  • resolveConstantDesc(Lookup lookup): 返回描述此字符串常量的常量描述符(Java 12 新增)。

10. 格式化和处理

10.1 格式化字符串
  • format(Locale l, String format, Object… args): 使用指定的语言环境和格式字符串创建新字符串。
  • format(String format, Object… args): 使用默认语言环境和格式字符串创建新字符串。
10.2 分割字符串
  • split(String regex): 使用正则表达式分割字符串,并返回分割后的字符串数组。
  • split(String regex, int limit): 使用正则表达式分割字符串,最多返回指定数量的子字符串。

这种更加细致的分类和描述将有助于你更深入地理解和使用 String 类的方法。

(三)测试用例

为了测试 String 类的所有方法,我们需要编写一个详细的测试用例。以下是每个方法的测试用例,包括输入、预期输出和实际输出的对比,以确保方法的正确性。

1. 创建和转换

1.1 从基本类型创建字符串
public class StringCreationTest {
    public static void main(String[] args) {
        // Test valueOf for boolean
        System.out.println(String.valueOf(true)); // "true"
        System.out.println(String.valueOf(false)); // "false"

        // Test valueOf for char
        System.out.println(String.valueOf('a')); // "a"

        // Test valueOf for double
        System.out.println(String.valueOf(123.45)); // "123.45"

        // Test valueOf for float
        System.out.println(String.valueOf(123.45f)); // "123.45"

        // Test valueOf for int
        System.out.println(String.valueOf(123)); // "123"

        // Test valueOf for long
        System.out.println(String.valueOf(123L)); // "123"
    }
}
1.2 从对象和数组创建字符串
public class StringFromObjectArrayTest {
    public static void main(String[] args) {
        // Test valueOf for Object
        System.out.println(String.valueOf(new Object())); // Object's toString output
        System.out.println(String.valueOf((Object) null)); // "null"

        // Test valueOf for char array
        char[] charArray = {'H', 'e', 'l', 'l', 'o'};
        System.out.println(String.valueOf(charArray)); // "Hello"
        System.out.println(String.valueOf(charArray, 1, 3)); // "ell"
    }
}
1.3 字符数组转换
public class StringToCharArrayTest {
    public static void main(String[] args) {
        // Test toCharArray
        String str = "Hello";
        char[] charArray = str.toCharArray();
        System.out.println(java.util.Arrays.toString(charArray)); // [H, e, l, l, o]
    }
}
1.4 字符串表示
public class StringToStringTest {
    public static void main(String[] args) {
        // Test toString
        String str = "Hello";
        System.out.println(str.toString()); // "Hello"
    }
}

2. 比较和匹配

2.1 内容比较
public class StringEqualsTest {
    public static void main(String[] args) {
        // Test equals
        String str1 = "Hello";
        String str2 = "Hello";
        String str3 = "hello";
        System.out.println(str1.equals(str2)); // true
        System.out.println(str1.equals(str3)); // false

        // Test equalsIgnoreCase
        System.out.println(str1.equalsIgnoreCase(str3)); // true
    }
}
2.2 字典顺序比较
public class StringCompareToTest {
    public static void main(String[] args) {
        // Test compareTo
        String str1 = "Hello";
        String str2 = "World";
        String str3 = "Hello";
        System.out.println(str1.compareTo(str2)); // Negative number (str1 < str2)
        System.out.println(str1.compareTo(str3)); // 0 (str1 == str3)

        // Test compareToIgnoreCase
        String str4 = "hello";
        System.out.println(str1.compareToIgnoreCase(str4)); // 0 (str1 == str4)
    }
}
2.3 内容相等性比较
public class StringContentEqualsTest {
    public static void main(String[] args) {
        // Test contentEquals with CharSequence
        String str1 = "Hello";
        StringBuilder str2 = new StringBuilder("Hello");
        System.out.println(str1.contentEquals(str2)); // true

        // Test contentEquals with StringBuffer
        StringBuffer str3 = new StringBuffer("Hello");
        System.out.println(str1.contentEquals(str3)); // true
    }
}
2.4 局部比较
public class StringRegionMatchesTest {
    public static void main(String[] args) {
        // Test regionMatches
        String str1 = "HelloWorld";
        String str2 = "WORLD";
        System.out.println(str1.regionMatches(5, str2, 0, 5)); // false
        System.out.println(str1.regionMatches(true, 5, str2, 0, 5)); // true
    }
}
2.5 前缀和后缀匹配
public class StringPrefixSuffixTest {
    public static void main(String[] args) {
        // Test startsWith
        String str = "HelloWorld";
        System.out.println(str.startsWith("Hello")); // true
        System.out.println(str.startsWith("World", 5)); // true

        // Test endsWith
        System.out.println(str.endsWith("World")); // true
    }
}
2.6 正则表达式匹配
public class StringMatchesTest {
    public static void main(String[] args) {
        // Test matches
        String str = "Hello123";
        System.out.println(str.matches("\\w+")); // true
        System.out.println(str.matches("\\d+")); // false
    }
}

3. 搜索和查找

3.1 查找字符
public class StringIndexOfCharTest {
    public static void main(String[] args) {
        // Test indexOf for char
        String str = "HelloWorld";
        System.out.println(str.indexOf('W')); // 5
        System.out.println(str.indexOf('o', 5)); // 7

        // Test lastIndexOf for char
        System.out.println(str.lastIndexOf('o')); // 7
        System.out.println(str.lastIndexOf('o', 6)); // 4
    }
}
3.2 查找子字符串
public class StringIndexOfStringTest {
    public static void main(String[] args) {
        // Test indexOf for substring
        String str = "HelloWorld";
        System.out.println(str.indexOf("World")); // 5
        System.out.println(str.indexOf("o", 5)); // 7

        // Test lastIndexOf for substring
        System.out.println(str.lastIndexOf("World")); // 5
        System.out.println(str.lastIndexOf("o", 6)); // 4
    }
}
3.3 包含检查
public class StringContainsTest {
    public static void main(String[] args) {
        // Test contains
        String str = "HelloWorld";
        System.out.println(str.contains("World")); // true
        System.out.println(str.contains("world")); // false
    }
}

4. 修改和操作

4.1 字符串拼接
public class StringConcatTest {
    public static void main(String[] args) {
        // Test concat
        String str1 = "Hello";
        String str2 = "World";
        System.out.println(str1.concat(str2)); // "HelloWorld"
    }
}
4.2 替换字符串内容
public class StringReplaceTest {
    public static void main(String[] args) {
        // Test replace for char
        String str = "HelloWorld";
        System.out.println(str.replace('o', 'a')); // "HellaWarld"

        // Test replace for CharSequence
        System.out.println(str.replace("World", "Java")); // "HelloJava"

        // Test replaceAll
        String regexStr = "Hello123World";
        System.out.println(regexStr.replaceAll("\\d+", "456")); // "Hello456World"

        // Test replaceFirst
        System.out.println(regexStr.replaceFirst("\\d+", "456")); // "Hello456World"
    }
}
4.3 提取子字符串
public class StringSubstringTest {
    public static void main(String[] args) {
        // Test substring
        String str = "HelloWorld";
        System.out.println(str.substring(5)); // "World"
        System.out.println(str.substring(0, 5)); // "Hello"
    }
}
4.4 提取字符序列
public class StringSubSequenceTest {
    public static void main(String[] args) {
        // Test subSequence
        String str = "HelloWorld";
        CharSequence seq = str.subSequence(5, 10);
        System.out.println(seq); // "World"
    }
}
4.5 去除空白字符
public class StringTrimTest {
    public static void main(String[] args) {
        // Test trim
        String str = "   HelloWorld   ";
        System.out.println(str.trim()); // "HelloWorld"

        // Test strip (Java 11+)
        String unicodeStr = "\u2000HelloWorld\u2000";
        System.out.println(unicodeStr.strip()); // "HelloWorld"
        System.out.println(unicodeStr.stripLeading()); // "HelloWorld\u2000"
        System.out.println(unicodeStr.stripTrailing()); // "\u2000HelloWorld"
    }
}
4.6 重复字符串
public class StringRepeatTest {
    public static void main(String[] args) {
        // Test repeat (Java 11+)
        String str = "Hello";
        System.out.println(str.repeat(3)); // "HelloHelloHello"
    }
}
4.7 缩进字符串
public class StringIndentTest {
    public static void main(String[] args) {
        // Test indent (Java 12+)
        String str = "Hello\nWorld";
        System.out.println(str.indent(4)); // Adds 4 spaces to each line
        System.out.println(str.indent(-2)); // Removes 2 spaces from each line
    }
}
4.8 字符串变换
import java.util.function.Function;

public class StringTransformTest {
    public static void main(String[] args) {
        // Test transform (Java 12+)
        String str = "HelloWorld";
        Function<String, String> upperCaseFunction = String::toUpperCase;
        System.out.println(str.transform(upperCaseFunction)); // "HELLOWORLD"
    }
}

5. 信息和状态

5.1 长度和空状态检查
public class StringLengthTest {
    public static void main(String[] args) {
        // Test length
        String str = "HelloWorld";
        System.out.println(str.length()); // 10

        // Test isEmpty
        String emptyStr = "";
        System.out.println(emptyStr.isEmpty()); // true

        // Test isBlank (Java 11+)
        String blankStr = "   ";
        System.out.println(blankStr.isBlank()); // true
    }
}
5.2 哈希码
public class StringHashCodeTest {
    public static void main(String[] args) {
        // Test hashCode
        String str = "HelloWorld";
        System.out.println(str.hashCode()); // Hash code of the string
    }
}
5.3 类信息
public class StringClassTest {
    public static void main(String[] args) {
        // Test getClass
        String str = "HelloWorld";
        System.out.println(str.getClass()); // class java.lang.String
    }
}

6. 字符和字节处理

6.1 获取字符和代码点
public class StringCharCodePointTest {
    public static void main(String[] args) {
        // Test charAt
        String str = "HelloWorld";
        System.out.println(str.charAt(1)); // 'e'

        // Test codePointAt
        System.out.println(str.codePointAt(1)); // Unicode code point of 'e'

        // Test codePointBefore
        System.out.println(str.codePointBefore(1)); // Unicode code point of 'H'

        // Test codePointCount
        System.out.println(str.codePointCount(0, str.length())); // Number of code points

        // Test offsetByCodePoints
        System.out.println(str.offsetByCodePoints(1, 3)); // Index after moving 3 code points from index 1
    }
}
6.2 转换为字节数组
import java.nio.charset.StandardCharsets;

public class StringGetBytesTest {
    public static void main(String[] args) {
        // Test getBytes
        String str = "HelloWorld";
        byte[] defaultBytes = str.getBytes();
        System.out.println(java.util.Arrays.toString(defaultBytes)); // Byte array in default charset

        // Test getBytes with Charset
        byte[] utf8Bytes = str.getBytes(StandardCharsets.UTF_8);
        System.out.println(java.util.Arrays.toString(utf8Bytes)); // Byte array in UTF-8

        // Test getBytes with String charset
        try {
            byte[] utf8Bytes2 = str.getBytes("UTF-8");
            System.out.println(java.util.Arrays.toString(utf8Bytes2)); // Byte array in UTF-8
        } catch (java.io.UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // Test getBytes with char range
        byte[] rangeBytes = new byte[5];
        str.getBytes(0, 5, rangeBytes, 0);
        System.out.println(java.util.Arrays.toString(rangeBytes)); // Byte array for specified range
    }
}
6.3 转换为字符数组
public class StringGetCharsTest {
    public static void main(String[] args) {
        // Test getChars
        String str = "HelloWorld";
        char[] charArray = new char[5];
        str.getChars(0, 5, charArray, 0);
        System.out.println(java.util.Arrays.toString(charArray)); // Char array for specified range
    }
}

7. 流和迭代

7.1 创建字符流和代码点流
import java.util.stream.IntStream;

public class StringCharsStreamTest {
    public static void main(String[] args) {
        // Test chars stream
        String str = "HelloWorld";
        IntStream charStream = str.chars();
        charStream.forEach(c -> System.out.print((char) c)); // "HelloWorld"
        System.out.println();

        // Test codePoints stream
        IntStream codePointStream = str.codePoints();
        codePointStream.forEach(cp -> System.out.print(Character.toChars(cp)));
        System.out.println(); // "HelloWorld"
    }
}
7.2 行流处理
import java.util.stream.Stream;

public class StringLinesTest {
    public static void main(String[] args) {
        // Test lines (Java 11+)
        String str = "Hello\nWorld\nJava";
        Stream<String> linesStream = str.lines();
        linesStream.forEach(System.out::println); // Prints each line separately
    }
}

8. 线程和同步

public class StringThreadSyncTest {
    public static void main(String[] args) {
        // Test notify, notifyAll, and wait
        String str = "HelloWorld";

        synchronized (str) {
            try {
                str.wait(1000); // Wait for 1 second
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            str.notify(); // Notify one waiting thread
            str.notifyAll(); // Notify all waiting threads
        }
    }
}

9. 高级和特殊

public class StringInternTest {
    public static void main(String[] args) {
        // Test intern
        String str1 = new String("HelloWorld");
        String internedStr = str1.intern();
        System.out.println(str1 == internedStr); // false
        System.out.println("HelloWorld" == internedStr); // true

        // Test describeConstable (Java 12+)
        String str2 = "HelloWorld";
        System.out.println(str2.describeConstable().get()); // Optional[String]

        // Test resolveConstantDesc (Java 12+)
        System.out.println(str2.resolveConstantDesc(null)); // ConstantDesc for String
    }
}

10. 格式化和处理

10.1 格式化字符串
import java.util.Locale;

public class StringFormatTest {
    public static void main(String[] args) {
        // Test format with Locale
        String formattedStr1 = String.format(Locale.US, "Hello %s", "World");
        System.out.println(formattedStr1); // "Hello World"

        // Test format without Locale
        String formattedStr2 = String.format("Hello %s", "Java");
        System.out.println(formattedStr2); // "Hello Java"
    }
}
10.2 分割字符串
public class StringSplitTest {
    public static void main(String[] args) {
        // Test split
        String str = "Hello,World,Java";
        String[] splitArray = str.split(",");
        System.out.println(java.util.Arrays.toString(splitArray)); // ["Hello", "World", "Java"]

        // Test split with limit
        String[] limitedSplitArray = str.split(",", 2);
        System.out.println(java.util.Arrays.toString(limitedSplitArray)); // ["Hello", "World,Java"]
    }
}

这些测试用例涵盖了 String 类的所有方法。你可以将这些代码片段分别放在 Java 文件中并运行它们,以验证每个方法的功能和行为。

二、CharSequence

CharSequence是Java中表示字符序列的接口,它被多个类(如StringStringBufferStringBuilder等)实现。由于CharSequence是一个接口,它定义了一些基础方法,这些方法在实现类中有具体的实现。下面我们将详细讲解CharSequence接口中的所有方法,并按用途、功能、目的、作用等进行分类和整理,最后给出使用场景和测试用例。

CharSequence接口方法

CharSequence接口中主要包含以下方法:

  1. char charAt(int index):返回指定索引处的字符。
  2. int length():返回字符序列的长度。
  3. CharSequence subSequence(int start, int end):返回此字符序列中指定范围的子序列。
  4. String toString():返回此字符序列的字符串表示形式。

方法详细讲解

1. char charAt(int index)
  • 功能:根据给定的索引返回字符序列中的字符。
  • 用途:在字符序列中查找和操作特定位置的字符。
  • 使用场景:需要访问特定位置的字符时(如字符串遍历、字符查找)。
示例代码:
CharSequence cs = "Hello, World!";
char ch = cs.charAt(7);
System.out.println(ch); // 输出: W
2. int length()
  • 功能:返回字符序列的长度。
  • 用途:获取字符序列的总长度。
  • 使用场景:需要知道字符序列的长度以进行遍历或其他操作时。
示例代码:
CharSequence cs = "Hello, World!";
int len = cs.length();
System.out.println(len); // 输出: 13
3. CharSequence subSequence(int start, int end)
  • 功能:返回字符序列中指定范围的子序列。
  • 用途:提取字符序列中的一部分。
  • 使用场景:需要从字符序列中提取子字符串或子序列时。
示例代码:
CharSequence cs = "Hello, World!";
CharSequence subCs = cs.subSequence(7, 12);
System.out.println(subCs); // 输出: World
4. String toString()
  • 功能:返回字符序列的字符串表示形式。
  • 用途:将字符序列转换为String对象,便于字符串操作。
  • 使用场景:需要将CharSequence转换为String进行处理时。
示例代码:
CharSequence cs = "Hello, World!";
String str = cs.toString();
System.out.println(str); // 输出: Hello, World!

分类整理

1. 获取字符
  • 方法char charAt(int index)
  • 用途:在字符序列中查找和操作特定位置的字符。
  • 示例场景:遍历字符序列、字符查找。
2. 获取长度
  • 方法int length()
  • 用途:获取字符序列的总长度。
  • 示例场景:遍历字符序列、验证长度。
3. 提取子序列
  • 方法CharSequence subSequence(int start, int end)
  • 用途:提取字符序列中的一部分。
  • 示例场景:截取子字符串、子序列分析。
4. 转换为字符串
  • 方法String toString()
  • 用途:将字符序列转换为String对象,便于字符串操作。
  • 示例场景:转换为String进行进一步处理。

使用场景

CharSequence接口可以用在各种需要处理字符序列的场景中,以下是一些典型使用场景:

  1. 字符串遍历:通过charAt方法遍历字符串中的每个字符。
  2. 子字符串提取:通过subSequence方法提取字符串中的子序列。
  3. 字符查找:通过charAt方法查找特定位置的字符。
  4. 长度验证:通过length方法验证字符序列的长度。
  5. 转换处理:通过toString方法将CharSequence转换为String进行进一步处理。

整合示例

下面是一个实际应用中的综合示例,用于展示如何使用CharSequence接口中定义的方法:

public class CharSequenceExample {
    public static void main(String[] args) {
        CharSequence cs = "Hello, CharSequence!";
        
        // 1. 获取字符
        for (int i = 0; i < cs.length(); i++) {
            System.out.print(cs.charAt(i) + " ");
        }
        System.out.println();
        
        // 2. 获取长度
        System.out.println("Length: " + cs.length());
        
        // 3. 提取子序列
        CharSequence subCs1 = cs.subSequence(7, 18);
        System.out.println("SubSequence 1: " + subCs1);
        
        CharSequence subCs2 = cs.subSequence(0, 5);
        System.out.println("SubSequence 2: " + subCs2);
        
        // 4. 转换为字符串
        String str = cs.toString();
        System.out.println("String: " + str);
        
        // 使用CharSequence的多态性
        manipulateCharSequence(cs);
        manipulateCharSequence(new StringBuilder("StringBuilder Example"));
        manipulateCharSequence(new StringBuffer("StringBuffer Example"));
    }
    
    public static void manipulateCharSequence(CharSequence cs) {
        System.out.println("Manipulating CharSequence: " + cs);
        for (int i = 0; i < cs.length(); i++) {
            System.out.print(cs.charAt(i) + " ");
        }
        System.out.println();
    }
}

三、StringBuffer

StringBuffer 类是 Java 中用于创建可变字符串的类,与 String 类不同,StringBuffer 是可变的,这意味着可以对其进行修改而不会创建新的对象。StringBuffer 是线程安全的,因为它的所有方法都是同步的。StringBuffer 类提供了许多方法来操作字符串,如添加、删除、插入和反转等。
以下是对 StringBuffer 类中的所有方法的详细讲解,包括其参数、作用、用途、使用场景,并提供详细的示例代码,帮助你理解和熟练运用这些方法。

一、构造方法

1. StringBuffer()

功能: 创建一个不包含任何字符的字符串缓冲区,初始容量为 16。
示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer();
        System.out.println("Initial capacity: " + sb.capacity());
    }
}
2. StringBuffer(int capacity)

功能: 创建一个不包含任何字符的字符串缓冲区,初始容量由参数指定。
参数:

  • capacity - 初始容量。

示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer(50);
        System.out.println("Initial capacity: " + sb.capacity());
    }
}
3. StringBuffer(String str)

功能: 创建一个字符串缓冲区,包含与指定字符串相同的字符,初始容量为字符串长度加 16。
参数:

  • str - 初始内容。

示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Hello");
        System.out.println("Content: " + sb.toString());
    }
}
4. StringBuffer(CharSequence seq)

功能: 创建一个字符串缓冲区,包含与指定字符序列相同的字符,初始容量为字符序列长度加 16。
参数:

  • seq - 初始内容。

示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Hello");
        System.out.println("Content: " + sb.toString());
    }
}

二、字符操作方法

1. int length()

功能: 返回字符串缓冲区的长度。
返回值: int - 缓冲区的长度。
示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Hello");
        System.out.println("Length: " + sb.length());
    }
}
2. int capacity()

功能: 返回字符串缓冲区的当前容量。
返回值: int - 缓冲区的容量。
示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Hello");
        System.out.println("Capacity: " + sb.capacity());
    }
}
3. void ensureCapacity(int minimumCapacity)

功能: 确保字符串缓冲区至少具有指定的最小容量。
参数:

  • minimumCapacity - 最小容量。

示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer();
        System.out.println("Initial capacity: " + sb.capacity());
        sb.ensureCapacity(100);
        System.out.println("New capacity: " + sb.capacity());
    }
}
4. void trimToSize()

功能: 将字符串缓冲区的容量缩减为当前内容的长度。
示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer(100);
        sb.append("Hello");
        System.out.println("Capacity before trim: " + sb.capacity());
        sb.trimToSize();
        System.out.println("Capacity after trim: " + sb.capacity());
    }
}

三、字符增删改查方法

1. StringBuffer append(Object obj)

功能: 将对象的字符串表示形式追加到此字符串缓冲区。
参数:

  • obj - 要追加的对象。

返回值: StringBuffer - 当前的字符串缓冲区。
示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Hello");
        sb.append(" World");
        System.out.println("Content: " + sb.toString());
    }
}
2. StringBuffer append(String str)

功能: 将指定的字符串追加到此字符串缓冲区。
参数:

  • str - 要追加的字符串。

返回值: StringBuffer - 当前的字符串缓冲区。
示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Hello");
        sb.append(" World");
        System.out.println("Content: " + sb.toString());
    }
}
3. StringBuffer append(CharSequence s)

功能: 将指定的字符序列追加到此字符串缓冲区。
参数:

  • s - 要追加的字符序列。

返回值: StringBuffer - 当前的字符串缓冲区。
示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Hello");
        sb.append(" World");
        System.out.println("Content: " + sb.toString());
    }
}
4. StringBuffer append(char[] str)

功能: 将字符数组追加到此字符串缓冲区。
参数:

  • str - 要追加的字符数组。

返回值: StringBuffer - 当前的字符串缓冲区。
示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Hello");
        char[] chars = {' ', 'W', 'o', 'r', 'l', 'd'};
        sb.append(chars);
        System.out.println("Content: " + sb.toString());
    }
}
5. StringBuffer append(boolean b)

功能: 将布尔值追加到此字符串缓冲区。
参数:

  • b - 要追加的布尔值。

返回值: StringBuffer - 当前的字符串缓冲区。
示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Boolean value: ");
        sb.append(true);
        System.out.println("Content: " + sb.toString());
    }
}
6. StringBuffer append(char c)

功能: 将字符追加到此字符串缓冲区。
参数:

  • c - 要追加的字符。

返回值: StringBuffer - 当前的字符串缓冲区。
示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Char value: ");
        sb.append('A');
        System.out.println("Content: " + sb.toString());
    }
}
7. StringBuffer append(int i)

功能: 将整数追加到此字符串缓冲区。
参数:

  • i - 要追加的整数。

返回值: StringBuffer - 当前的字符串缓冲区。
示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Int value: ");
        sb.append(123);
        System.out.println("Content: " + sb.toString());
    }
}
8. StringBuffer append(long l)

功能: 将长整数追加到此字符串缓冲区。
参数:

  • l - 要追加的长整数。

返回值: StringBuffer - 当前的字符串缓冲区。
示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Long value: ");
        sb.append(123456789L);
        System.out.println("Content: " + sb.toString());
    }
}
9. StringBuffer append(float f)

功能: 将浮点数追加到此字符串缓冲区。
参数:

  • f - 要追加的浮点数。

返回值: StringBuffer - 当前的字符串缓冲区。
示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Float value: ");
        sb.append(123.45f);
        System.out.println("Content: " + sb.toString());
    }
}
10. StringBuffer append(double d)

功能: 将双精度数追加到此字符串缓冲区。
参数:

  • d - 要追加的双精度数。

返回值: StringBuffer - 当前的字符串缓冲区。
示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Double value: ");
        sb.append(123.456789);
        System.out.println("Content: " + sb.toString());
    }
}
11. StringBuffer appendCodePoint(int codePoint)

功能: 将 Unicode 代码点表示的字符追加到此字符串缓冲区。
参数:

  • codePoint - 要追加的 Unicode 代码点。

返回值: StringBuffer - 当前的字符串缓冲区。
示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Unicode character: ");
        sb.appendCodePoint(65); // Unicode for 'A'
        System.out.println("Content: " + sb.toString());
    }
}
12. char charAt(int index)

功能: 返回指定索引处的字符。
参数:

  • index - 字符的索引。

返回值: char - 指定索引处的字符。
示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Hello");
        char c = sb.charAt(1);
        System.out.println("Character at index 1: " + c);
    }
}
13. void setCharAt(int index, char ch)

功能: 将指定索引处的字符设置为指定的字符。
参数:

  • index - 要设置的字符的索引。
  • ch - 要设置的字符。

示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Hello");
        sb.setCharAt(1, 'a');
        System.out.println("Content after setCharAt: " + sb.toString());
    }
}
14. StringBuffer insert(int offset, Object obj)

功能: 在指定位置插入对象的字符串表示形式。
参数:

  • offset - 插入位置的索引。
  • obj - 要插入的对象。

返回值: StringBuffer - 当前的字符串缓冲区。
示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Hello");
        sb.insert(1, "ey");
        System.out.println("Content after insert: " + sb.toString());
    }
}
15. StringBuffer insert(int offset, String str)

功能: 在指定位置插入字符串。
参数:

  • offset - 插入位置的索引。
  • str - 要插入的字符串。

返回值: StringBuffer - 当前的字符串缓冲区。
示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Hello");
        sb.insert(1, "ey");
        System.out.println("Content after insert: " + sb.toString());
    }
}
16. StringBuffer insert(int offset, char[] str)

功能: 在指定位置插入字符数组。
参数:

  • offset - 插入位置的索引。
  • str - 要插入的字符数组。

返回值: StringBuffer - 当前的字符串缓冲区。
示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Hello");
        char[] chars = {'e', 'y'};
        sb.insert(1, chars);
        System.out.println("Content after insert: " + sb.toString());
    }
}
17. StringBuffer delete(int start, int end)

功能: 删除从指定开始位置到结束位置的子字符串。
参数:

  • start - 删除的开始索引。
  • end - 删除的结束索引。

返回值: StringBuffer - 当前的字符串缓冲区。
示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Hello World");
        sb.delete(5, 11);
        System.out.println("Content after delete: " + sb.toString());
    }
}
18. StringBuffer deleteCharAt(int index)

功能: 删除指定位置的字符。
参数:

  • index - 要删除的字符的索引。

返回值: StringBuffer - 当前的字符串缓冲区。
示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Hello");
        sb.deleteCharAt(1);
        System.out.println("Content after deleteCharAt: " + sb.toString());
    }
}
19. StringBuffer replace(int start, int end, String str)

功能: 用指定字符串替换从开始索引到结束索引的子字符串。
参数:

  • start - 替换的开始索引。
  • end - 替换的结束索引。
  • str - 替换的字符串。

返回值: StringBuffer - 当前的字符串缓冲区。
示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Hello World");
        sb.replace(6, 11, "Java");
        System.out.println("Content after replace: " + sb.toString());
    }
}
20. String substring(int start)

功能: 返回从指定开始索引到缓冲区末尾的子字符串。
参数:

  • start - 子字符串的开始索引。

返回值: String - 子字符串。
示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Hello World");
        String sub = sb.substring(6);
        System.out.println("Substring: " + sub);
    }
}
21. String substring(int start, int end)

功能: 返回从指定开始索引到结束索引的子字符串。
参数:

  • start - 子字符串的开始索引。
  • end - 子字符串的结束索引。

返回值: String - 子字符串。
示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Hello World");
        String sub = sb.substring(6, 11);
        System.out.println("Substring: " + sub);
    }
}
22. void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

功能: 将缓冲区中的字符复制到目标字符数组中。
参数:

  • srcBegin - 源字符的起始索引。
  • srcEnd - 源字符的结束索引。
  • dst - 目标字符数组。
  • dstBegin - 目标字符数组的起始索引。

示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Hello World");
        char[] chars = new char[5];
        sb.getChars(0, 5, chars, 0);
        System.out.println("Chars: " + new String(chars));
    }
}
23. void setLength(int newLength)

功能: 设置缓冲区的长度。如果新长度小于当前长度,则缩短缓冲区;否则用空字符 (\u0000) 填充。
参数:

  • newLength - 新长度。

示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Hello");
        sb.setLength(10);
        System.out.println("Content after setLength: " + sb.toString());
        System.out.println("Length after setLength: " + sb.length());
    }
}
24. StringBuffer reverse()

功能: 反转缓冲区中的字符顺序。
返回值: StringBuffer - 当前的字符串缓冲区。
示例:

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Hello");
        sb.reverse();
        System.out.println("

四、StringBuilder

Java中的StringBuilder类是一个可变的字符序列,它与StringBuffer类似,但不是线程安全的。StringBuilder通常用于单线程环境,以提高性能。以下是StringBuilder类中的所有方法,按照用途和功能进行分类整理,并附带测试用例。

1. 构造方法

  • StringBuilder():创建一个空的StringBuilder对象,初始容量为16个字符。
  • StringBuilder(int capacity):创建一个空的StringBuilder对象,初始容量由参数指定。
  • StringBuilder(String str):创建一个包含指定字符串内容的StringBuilder对象。
  • StringBuilder(CharSequence seq):创建一个包含指定字符序列内容的StringBuilder对象。
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder(20);
StringBuilder sb3 = new StringBuilder("Hello");
StringBuilder sb4 = new StringBuilder("World");
System.out.println(sb1); // 输出: 
System.out.println(sb2); // 输出: 
System.out.println(sb3); // 输出: Hello
System.out.println(sb4); // 输出: World

2. 追加和插入

  • StringBuilder append(boolean b):将布尔值追加到字符序列中。
  • StringBuilder append(char c):将字符追加到字符序列中。
  • StringBuilder append(char[] str):将字符数组追加到字符序列中。
  • StringBuilder append(char[] str, int offset, int len):将字符数组的指定部分追加到字符序列中。
  • StringBuilder append(CharSequence s):将字符序列追加到字符序列中。
  • StringBuilder append(CharSequence s, int start, int end):将字符序列的指定部分追加到字符序列中。
  • StringBuilder append(double d):将双精度浮点数追加到字符序列中。
  • StringBuilder append(float f):将单精度浮点数追加到字符序列中。
  • StringBuilder append(int i):将整数追加到字符序列中。
  • StringBuilder append(long lng):将长整数追加到字符序列中。
  • StringBuilder append(Object obj):将对象追加到字符序列中。
  • StringBuilder append(String str):将字符串追加到字符序列中。
  • StringBuilder append(StringBuffer sb):将StringBuffer对象追加到字符序列中。
  • StringBuilder insert(int offset, boolean b):将布尔值插入到字符序列中。
  • StringBuilder insert(int offset, char c):将字符插入到字符序列中。
  • StringBuilder insert(int offset, char[] str):将字符数组插入到字符序列中。
  • StringBuilder insert(int index, char[] str, int offset, int len):将字符数组的指定部分插入到字符序列中。
  • StringBuilder insert(int dstOffset, CharSequence s):将字符序列插入到字符序列中。
  • StringBuilder insert(int dstOffset, CharSequence s, int start, int end):将字符序列的指定部分插入到字符序列中。
  • StringBuilder insert(int offset, double d):将双精度浮点数插入到字符序列中。
  • StringBuilder insert(int offset, float f):将单精度浮点数插入到字符序列中。
  • StringBuilder insert(int offset, int i):将整数插入到字符序列中。
  • StringBuilder insert(int offset, long l):将长整数插入到字符序列中。
  • StringBuilder insert(int offset, Object obj):将对象插入到字符序列中。
  • StringBuilder insert(int offset, String str):将字符串插入到字符序列中。
StringBuilder sb5 = new StringBuilder("Hello");
sb5.append(" World");
System.out.println(sb5); // 输出: Hello World

sb5.insert(5, ", ");
System.out.println(sb5); // 输出: Hello, World

sb5.append(123);
System.out.println(sb5); // 输出: Hello, World123

sb5.insert(0, "Start: ");
System.out.println(sb5); // 输出: Start: Hello, World123

3. 删除和替换

  • StringBuilder delete(int start, int end):删除字符序列中指定范围的字符。
  • StringBuilder deleteCharAt(int index):删除字符序列中指定位置的字符。
  • StringBuilder replace(int start, int end, String str):用指定字符串替换字符序列中指定范围的字符。
StringBuilder sb6 = new StringBuilder("Hello, World!");
sb6.delete(5, 7);
System.out.println(sb6); // 输出: Hello World!

sb6.deleteCharAt(5);
System.out.println(sb6); // 输出: HelloWorld!

sb6.replace(5, 10, "Java");
System.out.println(sb6); // 输出: HelloJava!

4. 获取和设置

  • char charAt(int index):返回字符序列中指定位置的字符。
  • int codePointAt(int index):返回字符序列中指定位置的字符的Unicode代码点。
  • int codePointBefore(int index):返回字符序列中指定位置之前的字符的Unicode代码点。
  • int codePointCount(int beginIndex, int endIndex):返回字符序列中指定范围的Unicode代码点数。
  • int length():返回字符序列的长度。
  • int offsetByCodePoints(int index, int codePointOffset):返回从指定索引开始偏移指定代码点的索引。
  • void setCharAt(int index, char ch):设置字符序列中指定位置的字符。
  • void setLength(int newLength):设置字符序列的长度。
  • CharSequence subSequence(int start, int end):返回字符序列中指定范围的子序列。
  • String substring(int start):返回字符序列中从指定位置开始的子字符串。
  • String substring(int start, int end):返回字符序列中指定范围的子字符串。
StringBuilder sb7 = new StringBuilder("Hello, World!");
System.out.println(sb7.charAt(0)); // 输出: H
System.out.println(sb7.codePointAt(0)); // 输出: 72
System.out.println(sb7.codePointBefore(1)); // 输出: 72
System.out.println(sb7.codePointCount(0, 5)); // 输出: 5
System.out.println(sb7.length()); // 输出: 13
System.out.println(sb7.offsetByCodePoints(0, 5)); // 输出: 5

sb7.setCharAt(0, 'h');
System.out.println(sb7); // 输出: hello, World!

sb7.setLength(5);
System.out.println(sb7); // 输出: hello

System.out.println(sb7.subSequence(0, 3)); // 输出: hel
System.out.println(sb7.substring(0, 3)); // 输出: hel
System.out.println(sb7.substring(3)); // 输出: lo

5. 其他方法

  • StringBuilder reverse():反转字符序列。
  • void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin):将字符序列中的字符复制到目标字符数组中。
  • int capacity():返回当前容量。
  • void ensureCapacity(int minimumCapacity):确保容量至少等于指定的最小值。
  • void trimToSize():尝试减少存储空间。
StringBuilder sb8 = new StringBuilder("Hello");
sb8.reverse();
System.out.println(sb8); // 输出: olleH

char[] dst = new char[5];
sb8.getChars(0, 5, dst, 0);
System.out.println(new String(dst)); // 输出: olleH

System.out.println(sb8.capacity()); // 输出: 21 (初始容量为16,加上5个字符)

sb8.ensureCapacity(30);
System.out.println(sb8.capacity()); // 输出: 42 (至少为30,但通常是2倍加2)

sb8.trimToSize();
System.out.println(sb8.capacity()); // 输出: 5 (减少到实际字符数)

6. 总结与使用场景

  • 构造方法:用于创建StringBuilder对象,可以指定初始容量或包含初始字符串。
  • 追加和插入:用于向字符序列中追加或插入各种类型的数据。
  • 删除和替换:用于删除字符序列中的字符或替换指定范围的字符。
  • 获取和设置:用于获取字符序列中的字符、长度、子序列等,以及设置字符或长度。
  • 其他方法:用于反转字符序列、复制字符、管理容量等。

7. 使用场景

  • 动态字符串构建:当需要频繁修改字符串内容时,使用StringBuilder可以提高效率。
  • 字符串拼接:当需要进行大量字符串拼接操作时,使用StringBuilder可以避免创建大量临时字符串对象。
  • 字符串修改:当需要对字符串进行插入、删除、替换等操作时,使用StringBuilder更加方便。
  • 5
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值