java StringBuilder详解

阅读更多

StringBuilder 是一个可变的字符序列。它继承于AbstractStringBuilder,实现了CharSequence接口。
StringBuilder是非线程安全的。附件为大家提供了源代码,可以下载查看。

下面为大家提供一些实际的demo操作例子:

/**
 * StringBuilder 演示程序
 * @author zhouguohui
 */
import java.util.HashMap;

public class StringBuilderTest {

    public static void main(String[] args) {
        testOtherAPIs() ;
        testIndexAPIs() ;
        testInsertAPIs() ;
        testAppendAPIs() ;
        testReplaceAPIs() ;
        testDeleteAPIs() ;
    }

    /**
     * StringBuilder 的其它API示例
     */
    private static void testOtherAPIs() {

        System.out.println("-------------------------------- testOtherAPIs --------------------------------");

        StringBuilder sbuilder = new StringBuilder("0123456789");

        int cap = sbuilder.capacity();
        System.out.printf("cap=%d\n", cap);

        char c = sbuilder.charAt(6);
        System.out.printf("c=%c\n", c);

        char[] carr = new char[4];
        sbuilder.getChars(3, 7, carr, 0);
        for (int i=0; i 
  

     运行结果为:

-------------------------------- testOtherAPIs --------------------------------
cap=26
c=6
carr[0]=3 carr[1]=4 carr[2]=5 carr[3]=6 

-------------------------------- testIndexAPIs --------------------------------
sbuilder=abcAbcABCabCaBcAbCaBCabc
sbuilder.indexOf("bc")         = 1
sbuilder.indexOf("bc", 5)      = 22
sbuilder.lastIndexOf("bc")     = 22
sbuilder.lastIndexOf("bc", 4)  = 4

-------------------------------- testInsertAPIs -------------------------------
{3=three, 2=two, 1=one}
12345StringBUFFERStringBufferBUILDERStringBuilder12345100
true3.141591.414ABCabcde

-------------------------------- testAppendAPIs -------------------------------
abcdeABC1.4143.14159true
10012345StringBuilderBUILDERStringBufferBUFFERString12345
{3=three, 2=two, 1=one}
字符编码

-------------------------------- testReplaceAPIs ------------------------------
sbuilder=ABCDE3456789
sbuilder=9876543210
sbuilder=M123456789

-------------------------------- testDeleteAPIs -------------------------------
sbuilder=123789
str1=23789
str2=78
str3=78
  • StringBuilder.zip (1.8 KB)
  • 下载次数: 0

你可能感兴趣的:(java,StringBuilder)