0. Introduction to StringBuilder Type
The StringBuilder type is a mutable string type. The API of the StringBuilder type is basically the same as the API of the StringBuffer type. The only difference is that the use of StringBuilder assumes that it is in a single thread. In other words, StringBuilder is thread-insecure. When instantiating StringBuilder, it usually sets a capacity size by default, generally the length of the string parameter +16. StringBuilder inherits the abstract class AbstractStringBuilder, and the abstract class is implemented internally using character arrays, and the array can be dynamically expanded. Common methods provided by the StringBuilder class include append(), insert(), replace(), deleteCharAt(), indexOf(), reverse(), toString() and other methods, which can realize basic functions such as adding, deleting, modifying and searching of strings.
package date0812.demo1;public class Test3 { public static void main(String[] args) { StringBuilder stringBuilder = new StringBuilder("Eclipse"); //Add stringBuilder = stringBuilder.append(" software"); //Capacity int C = stringBuilder.capacity(); //Flip stringBuilder= stringBuilder.reverse(); System.out.println(C); System.out.println(stringBuilder); }} Running results:
23erawtfos espilcE
1. StringBuilder method
StringBuilder is a variable character sequence. It inherits from AbstractStringBuilder and implements the CharSequence interface.
StringBuffer is also a subclass inherited from AbstractStringBuilder; however, StringBuilder and StringBuffer are different. The former is non-thread-safe, while the latter is thread-safe.
The relationship diagram between StringBuilder and CharSequence is as follows:
List of StringBuilder methods:
StringBuilder()StringBuilder(int capacity)StringBuilder(CharSequence seq)StringBuilder(String str)StringBuilder append(float f)StringBuilder append(double d)StringBuilder append(boolean b)StringBuilder append(int i)StringBuilder append(long l)StringBuilder append(char c)StringBuilder append(char[] chars)StringBuilder append(char[] str, int offset, int len)StringBuilder append(String str)StringBuilder append(Object obj)StringBuilder append(StringBuffer sb)StringBuilder append(CharSequence csq)StringBuilder append(CharSequence csq, int start, int end)StringBuilder appendCodePoint(int codePoint)int capacity()char charAt(int index)int codePointAt(int index)int codePointBefore(int index)int codePointCount(int start, int end)StringBuilder delete(int start, int end)StringBuilder deleteCharAt(int index)void ensureCapacity(int min)void getChars(int start, int end, char[] dst, int dstStart)int indexOf(String subString, int start)int indexOf(String string)StringBuilder insert(int offset, boolean b)StringBuilder insert(int offset, int i)StringBuilder insert(int offset, long l)StringBuilder insert(int offset, float f)StringBuilder insert(int offset, double d)StringBuilder insert(int offset, char c)StringBuilder insert(int offset, char[] ch)StringBuilder insert(int offset, char[] str, int strOffset, int strLen)StringBuilder insert(int offset, String str)StringBuilder insert(int offset, Object obj)StringBuilder insert(int offset, CharSequence s)StringBuilder insert(int offset, CharSequence s, int start, int end)int lastIndexOf(String string)int lastIndexOf(String subString, int start)int length()int offsetByCodePoints(int index, int codePointOffset)StringBuilder replace(int start, int end, String string)StringBuilder reverse()void setCharAt(int index, char ch)void setLength(int length)CharSequence subSequence(int start, int end)String substring(int start)String substring(int start, int end)String toString()void trimToSize()
Since the source code of AbstractStringBuilder and StringBuilder is too long, the source code will not be listed here. Interested readers can study it themselves.
2. StringBuilder API test code
2.1 Insert (insert) related API in StringBuilder
The source code is as follows (StringBuilderInsertTest.java):
/** * StringBuilder 的insert()示例* * @author skywang */import java.util.HashMap;public class StringBuilderInsertTest { public static void main(String[] args) { testInsertAPIs() ; } /** * StringBuilder 的insert()示例*/ private static void testInsertAPIs() { System.out.println("-------------------------------- testInsertAPIs -------------------------------"); StringBuilder sbuilder = new StringBuilder(); // Insert the character array at position 0 sbuilder.insert(0, new char[]{'a','b','c','d','e'}); // Insert the character array at position 0. 0 represents the starting position of the character array, 3 represents the length sbuilder.insert(0, new char[]{'A','B','C','D','E'}, 0, 3); // Insert float sbuilder.insert(0, 1.414f); // Insert double sbuilder.insert(0, 3.14159d); // Insert boolean sbuilder.insert(0, true); // Insert char sbuilder.insert(0, '/n'); // Insert int sbuilder.insert(0, 100); // Insert long sbuilder.insert(0, 14159d); // Insert boolean sbuilder.insert(0, true); // Insert char sbuilder.insert(0, '/n'); // Insert int sbuilder.insert(0, 100); // Insert long sbuilder.insert(0, 12345L); // Insert the StringBuilder object sbuilder.insert(0, new StringBuilder("StringBuilder")); // Insert the StringBuilder object at position 0. 6 represents the start position (including) of the object inserted at position 0, 13 is the end position (excluding) sbuilder.insert(0, new StringBuilder("STRINGBUILDER"), 6, 13); // Insert the StringBuffer object at position 0. sbuilder.insert(0, new StringBuffer("StringBuffer")); // Insert the StringBuffer object at position 0. 6 represents the start position (including) of the object inserted at position 0, 12 is the end position (excluding) sbuilder.insert(0, new StringBuffer("STRINGBUFFER"), 6, 12); // Insert the String object at position 0. sbuilder.insert(0, "String"); // Insert the String object at position 0. 1 represents the start position (including) of the object inserted at position 0, 6 is the end position (excluding) sbuilder.insert(0, "0123456789", 1, 6); sbuilder.insert(0, '/n'); // Insert the Object object at position 0. Here we take HashMap as an example HashMap map = new HashMap(); map.put("1", "one"); map.put("2", "two"); map.put("3", "three"); sbuilder.insert(0, map); System.out.printf("%s/n/n", sbuilder); }} Running results:
-------------------------------- testInsertAPIs -------------------------------{3=three, 2=two, 1=one}12345StringBUFFERStringBufferBUILDERStringBuilder12345100true3.141591.414ABCabcde 2.2 Append (append) related APIs in StringBuilder
The source code is as follows (StringBuilderAppendTest.java):
/** * StringBuilder 的append()示例* * @author skywang */import java.util.HashMap;public class StringBuilderAppendTest { public static void main(String[] args) { testAppendAPIs() ; } /** * StringBuilder 的append()示例*/ private static void testAppendAPIs() { System.out.println("-------------------------------- testAppendAPIs -------------------------------"); StringBuilder sbuilder = new StringBuilder(); // Append character array sbuilder.append(new char[]{'a','b','c','d','e'}); // Append character array. 0 indicates the starting position of the character array, 3 indicates the length sbuilder.append(new char[]{'A','B','C','D','E'}, 0, 3); // Append float sbuilder.append(1.414f); // Append double sbuilder.append(3.14159d); // Append boolean sbuilder.append(true); // Append char sbuilder.append('/n'); // Append int sbuilder.append(100); // Append long sbuilder.append(12345L); // Append StringBuilder object sbuilder.append(new StringBuilder("StringBuilder")); // Append StringBuilder object. 6 indicates the start position (including) of the appended object, 13 is the end position (excluding) sbuilder.append(new StringBuilder("STRINGBUILDER"), 6, 13); // Append StringBuffer object. sbuilder.append(new StringBuffer("StringBuffer")); // Append StringBuffer object. 6 indicates the starting position (including) of the appended object, 12 is the end position (excluding) sbuilder.append(new StringBuffer("STRINGBUFFER"), 6, 12); // Append String object. sbuilder.append("String"); // Append String object. 1 indicates the start position (including) of the appended object, 6 is the end position (excluding) sbuilder.append("0123456789", 1, 6); sbuilder.append('/n'); // Append Object object. Here we take HashMap as an example HashMap map = new HashMap(); map.put("1", "one"); map.put("2", "two"); map.put("3", "three"); sbuilder.append(map); sbuilder.append('/n'); // Append unicode encoding sbuilder.appendCodePoint(0x5b57); // 0x5b57 is the unicode encoding sbuilder.appendCodePoint(0x7b26); // 0x7b26 is the unicode encoding sbuilder.appendCodePoint(0x7f16); // 0x7f16 is the "encoded" unicode encoding sbuilder.appendCodePoint(0x7801); // 0x7801 is the "encoded" unicode encoding System.out.printf("%s/n/n", sbuilder); }} Running results:
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2.3 Replace related APIs in StringBuilder
The source code is as follows (StringBuilderReplaceTest.java):
/** * StringBuilder 的replace()示例* * @author skywang */import java.util.HashMap;public class StringBuilderReplaceTest { public static void main(String[] args) { testReplaceAPIs() ; } /** * StringBuilder 的replace()示例*/ private static void testReplaceAPIs() { System.out.println("-------------------------------- testReplaceAPIs ------------------------------"); StringBuilder sbuilder; sbuilder = new StringBuilder("0123456789"); sbuilder.replace(0, 3, "ABCDE"); System.out.printf("sbuilder=%s/n", sbuilder); sbuilder = new StringBuilder("0123456789"); sbuilder.reverse(); System.out.printf("sbuilder=%s/n", sbuilder); sbuilder = new StringBuilder("0123456789"); sbuilder.setCharAt(0, 'M'); System.out.printf("sbuilder=%s/n", sbuilder); System.out.println(); }} Running results:
-------------------------------- testReplaceAPIs ------------------------------sbuilder=ABCDE3456789sbuilder=9876543210sbuilder=M123456789
2.4 Delete (delete) related API in StringBuilder
The source code is as follows (StringBuilderDeleteTest.java):
/** * StringBuilder 的delete()示例* * @author skywang */import java.util.HashMap;public class StringBuilderDeleteTest { public static void main(String[] args) { testDeleteAPIs() ; } /** * StringBuilder 的delete()示例*/ private static void testDeleteAPIs() { System.out.println("-------------------------------- testDeleteAPIs -------------------------------"); StringBuilder sbuilder = new StringBuilder("0123456789"); // Delete the character at position 0, the remaining character is "123456789". sbuilder.deleteCharAt(0); // Delete characters between position 3 (including) and position 6 (excluding), and the remaining characters are "123789". sbuilder.delete(3,6); // Get the string starting from position 1 in sb String str1 = sbuilder.substring(1); // Get the string from position 3 (including) to position 5 (excluding) in sb String str2 = sbuilder.substring(3, 5); // Get the string from position 3 (including) to position 5 (excluding) in sb String str3 = (String)sbuilder.subSequence(3, 5); System.out.printf("sbuilder=%s/nstr1=%s/nstr2=%s/nstr3=%s/n", sbuilder, str1, str2, str3); }} Running results:
-------------------------------- testDeleteAPIs -------------------------------sbuilder=123789str1=23789str2=78str3=78
2.5 Index-related API in StringBuilder
The source code is as follows (StringBuilderIndexTest.java):
/** * Index-related API demonstration in StringBuilder* * @author skywang */import java.util.HashMap;public class StringBuilderIndexTest { public static void main(String[] args) { testIndexAPIs() ; } /** * Index-related API demonstration in StringBuilder*/ private static void testIndexAPIs() { System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- StringBuilder sbuilder = new StringBuilder("abcAbcABCabCaBcAbCaBCabc"); System.out.printf("sbuilder=%s/n", sbuilder); // 1. From front to back, find the location where "bc" appears for the first time System.out.printf("%-30s = %d/n", "sbuilder.indexOf(/"bc/")", sbuilder.indexOf("bc")); // 2. From position 5, from front to back, find the location where "bc" appears for the first time System.out.printf("%-30s = %d/n", "sbuilder.indexOf(/"bc/", 5)", sbuilder.indexOf("bc", 5)); // 3. From back to front, find the location where "bc" appears for the first time System.out.printf("%-30s = %d/n", "sbuilder.lastIndexOf(/"bc/")", sbuilder.lastIndexOf("bc")); // 4. From back to front, find the location where "bc" appears for the first time System.out.printf("%-30s = %d/n", "sbuilder.lastIndexOf(/"bc/", 4)", sbuilder.lastIndexOf("bc", 4)); System.out.println(); }} Running results:
-------------------------------- testIndexAPIs --------------------------------sbuilder=abcAbcABCabCaBcAbCaBCabcsbuilder.indexOf("bc") = 1sbuilder.indexOf("bc", 5) = 22sbuilder.lastIndexOf("bc") = 22sbuilder.lastIndexOf("bc", 4) = 4 2.6 StringBuilder Remaining API
The source code is as follows (StringBuilderOtherTest.java):
/** * Other API examples of StringBuilder* * @author skywang */import java.util.HashMap;public class StringBuilderOtherTest { public static void main(String[] args) { testOtherAPIs() ; } /** * Other API examples of StringBuilder*/ private static void testOtherAPIs() { System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 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<carr.length; i++) System.out.printf("carr[%d]=%c ", i, carr[i]); System.out.println(); System.out.println(); }} Running results:
-------------------------------- testOtherAPIs --------------------------------cap=26c=6carr[0]=3 carr[1]=4 carr[2]=5 carr[3]=6
3. StringBuilder complete example
The following example is a complete StringBuilder demonstration program integrating the above examples. The source code is as follows (StringBuilderTest.java):
/** * StringBuilder demo program* * @author skywang */import java.util.HashMap;public class StringBuilderTest { public static void main(String[] args) { testOtherAPIs() ; testIndexAPIs() ; testInsertAPIs() ; testAppendAPIs() ; testReplaceAPIs() ; testDeleteAPIs() ; } /** * Other API examples of StringBuilder*/ 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<carr.length; i++) System.out.printf("carr[%d]=%c ", i, carr[i]); System.out.println(); System.out.println(); } /** * StringBuilder 中index相关API演示*/ private static void testIndexAPIs() { System.out.println("-------------------------------- testIndexAPIs --------------------------------"); StringBuilder sbuilder = new StringBuilder("abcAbcABCabCaBcAbCaBCabc"); System.out.printf("sbuilder=%s/n", sbuilder); // 1. From front to back, find the location where "bc" appears for the first time System.out.printf("%-30s = %d/n", "sbuilder.indexOf(/"bc/")", sbuilder.indexOf("bc")); // 2. From position 5, from front to back, find the location where "bc" appears for the first time System.out.printf("%-30s = %d/n", "sbuilder.indexOf(/"bc/", 5)", sbuilder.indexOf("bc", 5)); // 3. From back to front, find the location where "bc" appears for the first time System.out.printf("%-30s = %d/n", "sbuilder.lastIndexOf(/"bc/")", sbuilder.lastIndexOf("bc")); // 4. From back to front, find the location where "bc" appears for the first time System.out.printf("%-30s = %d/n", "sbuilder.lastIndexOf(/"bc/", 4)", sbuilder.lastIndexOf("bc", 4)); System.out.println(); } /** * StringBuilder 的replace()示例*/ private static void testReplaceAPIs() { System.out.println("-------------------------------- testReplaceAPIs ------------------------------"); StringBuilder sbuilder; sbuilder = new StringBuilder("0123456789"); sbuilder.replace(0, 3, "ABCDE"); System.out.printf("sbuilder=%s/n", sbuilder); sbuilder = new StringBuilder("0123456789"); sbuilder.reverse(); System.out.printf("sbuilder=%s/n", sbuilder); sbuilder = new StringBuilder("0123456789"); sbuilder.setCharAt(0, 'M'); System.out.printf("sbuilder=%s/n", sbuilder); System.out.println(); } /** * StringBuilder delete() example*/ private static void testDeleteAPIs() { System.out.println("---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- sbuilder.deleteCharAt(0); // Delete characters between position 3 (including) and position 6 (excluding), and the remaining characters are "123789". sbuilder.delete(3,6); // Get the string starting from position 1 in sb String str1 = sbuilder.substring(1); // Get the string from position 3 (including) to position 5 (excluding) in sb String str2 = sbuilder.substring(3, 5); // Get the string from position 3 (including) to position 5 (excluding) in sb String str3 = (String)sbuilder.subSequence(3, 5); System.out.printf("sbuilder=%s/nstr1=%s/nstr2=%s/nstr3=%s/n", sbuilder, str1, str2, str3); } /** * StringBuilder insert() example*/ private static void testInsertAPIs() { System.out.println("----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 0 represents the starting position of the character array, 3 represents the length sbuilder.insert(0, new char[]{'A','B','C','D','E'}, 0, 3); // Insert float sbuilder.insert(0, 1.414f); // Insert double sbuilder.insert(0, 3.14159d); // Insert boolean sbuilder.insert(0, true); // Insert char sbuilder.insert(0, '/n'); // Insert int sbuilder.insert(0, 100); // Insert long sbuilder.insert(0, 14159d); // Insert boolean sbuilder.insert(0, true); // Insert char sbuilder.insert(0, '/n'); // Insert int sbuilder.insert(0, 100); // Insert long sbuilder.insert(0, 12345L); // Insert the StringBuilder object sbuilder.insert(0, new StringBuilder("StringBuilder")); // Insert the StringBuilder object at position 0. 6 represents the start position (including) of the object inserted at position 0, 13 is the end position (excluding) sbuilder.insert(0, new StringBuilder("STRINGBUILDER"), 6, 13); // Insert the StringBuffer object at position 0. sbuilder.insert(0, new StringBuffer("StringBuffer")); // Insert the StringBuffer object at position 0. 6 represents the start position (including) of the object inserted at position 0, 12 is the end position (excluding) sbuilder.insert(0, new StringBuffer("STRINGBUFFER"), 6, 12); // Insert the String object at position 0. sbuilder.insert(0, "String"); // Insert the String object at position 0. 1 represents the start position (including) of the object inserted at position 0, 6 is the end position (excluding) sbuilder.insert(0, "0123456789", 1, 6); sbuilder.insert(0, '/n'); // Insert the Object object at position 0.此处以HashMap为例HashMap map = new HashMap(); map.put("1", "one"); map.put("2", "two"); map.put("3", "three"); sbuilder.insert(0, map); System.out.printf("%s/n/n", sbuilder); } /** * StringBuilder 的append()示例*/ private static void testAppendAPIs() { System.out.println("-------------------------------- testAppendAPIs ----------------------------------"); StringBuilder sbuilder = new StringBuilder(); // Append character array sbuilder.append(new char[]{'a','b','c','d','e'}); // Append character array. 0 indicates the starting position of the character array, 3 indicates the length sbuilder.append(new char[]{'A','B','C','D','E'}, 0, 3); // Append float sbuilder.append(1.414f); // Append double sbuilder.append(3.14159d); // Append boolean sbuilder.append(true); // Append char sbuilder.append('/n'); // Append int sbuilder.append(100); // Append long sbuilder.append(12345L); // Append StringBuilder object sbuilder.append(new StringBuilder("StringBuilder")); // Append StringBuilder object. 6 indicates the start position (including) of the appended object, 13 is the end position (excluding) sbuilder.append(new StringBuilder("STRINGBUILDER"), 6, 13); // Append StringBuffer object. sbuilder.append(new StringBuffer("StringBuffer")); // Append StringBuffer object. 6 indicates the starting position (including) of the appended object, 12 is the end position (excluding) sbuilder.append(new StringBuffer("STRINGBUFFER"), 6, 12); // Append String object. sbuilder.append("String"); // Append String object. 1 indicates the start position (including) of the appended object, 6 is the end position (excluding) sbuilder.append("0123456789", 1, 6); sbuilder.append('/n'); // Append Object object. Here we take HashMap as an example HashMap map = new HashMap(); map.put("1", "one"); map.put("2", "two"); map.put("3", "three"); sbuilder.append(map); sbuilder.append('/n'); // Append unicode encoding sbuilder.appendCodePoint(0x5b57); // 0x5b57 is the unicode encoding sbuilder.appendCodePoint(0x7b26); // 0x7b26 is the unicode encoding sbuilder.appendCodePoint(0x7f16); // 0x7f16 is the "encoded" unicode encoding sbuilder.appendCodePoint(0x7801); // 0x7801 is the "encoded" unicode encoding System.out.printf("%s/n/n", sbuilder); }}