20230516 java.lang.StringBuilder

介绍

  • java.lang.StringBuilder
  • public final class StringBuilder extends AbstractStringBuilder implements java.io.Serializable, Comparable<StringBuilder>, CharSequence
  • 此类提供与 StringBuffer 兼容的 API,但不保证线程安全
  • append 方法总是在构建器的末尾添加这些字符; insert 方法在指定点添加字符

构造函数

  • public StringBuilder()
  • public StringBuilder(int capacity)
  • public StringBuilder(String str)
  • public StringBuilder(CharSequence seq)

API

编辑等操作:

  • append
  • delete, deleteCharAt
  • insert
  • replace
  • reverse
  • toString

其他:

  • charAt
  • chars
  • compareTo
  • indexOf, lastIndexOf
  • isEmpty
  • length
  • subSequence, subString

代码示例

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class StringBuilderTest {

    @Test
    void testAppend() {
        StringBuilder builder = new StringBuilder("Hello");
        builder.append(" world");
        Assertions.assertEquals("Hello world", builder.toString());
    }

    @Test
    void testInsert() {
        StringBuilder builder = new StringBuilder("1234");
        builder.insert(2, "56");
        Assertions.assertEquals("125634", builder.toString());
    }

    @Test
    void testDelete() {
        StringBuilder builder = new StringBuilder("abcdefg");
        builder.delete(1, 3);
        Assertions.assertEquals("adefg", builder.toString());
    }

    @Test
    void testReverse() {
        StringBuilder builder = new StringBuilder("abcde");
        builder.reverse();
        Assertions.assertEquals("edcba", builder.toString());
    }

    @Test
    void testReplace() {
        StringBuilder builder = new StringBuilder("abcde");
        builder.replace(1, 3, "12");
        Assertions.assertEquals("a12de", builder.toString());
    }
    
}
posted @ 2023-08-28 09:47  流星<。)#)))≦  阅读(18)  评论(0编辑  收藏  举报