本章介绍StringBuilder以及它的API的详细使用方法。
转载请注明出处:http://www.cnblogs.com/skywang12345/p/string02.html
StringBuilder 简介
StringBuilder 是一个可变的字符序列。它继承于AbstractStringBuilder,实现了CharSequence接口。
StringBuffer 也是继承于AbstractStringBuilder的子类;但是,StringBuilder和StringBuffer不同,前者是非线程安全的,后者是线程安全的。
StringBuilder 和 CharSequence之间的关系图如下:
StringBuilder函数列表
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()
AbstractStringBuilder 和 StringBuilder源码
AbstractStringBuilder源码(基于jdk1.7.40)
package java.lang; import sun.misc.FloatingDecimal;
import java.util.Arrays; abstract class AbstractStringBuilder implements Appendable, CharSequence {
char[] value; int count; AbstractStringBuilder() {
} AbstractStringBuilder(int capacity) {
value = new char[capacity];
} public int length() {
return count;
} public int capacity() {
return value.length;
} public void ensureCapacity(int minimumCapacity) {
if (minimumCapacity > 0)
ensureCapacityInternal(minimumCapacity);
} private void ensureCapacityInternal(int minimumCapacity) {
// overflow-conscious code
if (minimumCapacity - value.length > 0)
expandCapacity(minimumCapacity);
} void expandCapacity(int minimumCapacity) {
int newCapacity = value.length * 2 + 2;
if (newCapacity - minimumCapacity < 0)
newCapacity = minimumCapacity;
if (newCapacity < 0) {
if (minimumCapacity < 0) // overflow
throw new OutOfMemoryError();
newCapacity = Integer.MAX_VALUE;
}
value = Arrays.copyOf(value, newCapacity);
} public void trimToSize() {
if (count < value.length) {
value = Arrays.copyOf(value, count);
}
} public void setLength(int newLength) {
if (newLength < 0)
throw new StringIndexOutOfBoundsException(newLength);
ensureCapacityInternal(newLength); if (count < newLength) {
for (; count < newLength; count++)
value[count] = '\0';
} else {
count = newLength;
}
} public char charAt(int index) {
if ((index < 0) || (index >= count))
throw new StringIndexOutOfBoundsException(index);
return value[index];
} public int codePointAt(int index) {
if ((index < 0) || (index >= count)) {
throw new StringIndexOutOfBoundsException(index);
}
return Character.codePointAt(value, index);
} public int codePointBefore(int index) {
int i = index - 1;
if ((i < 0) || (i >= count)) {
throw new StringIndexOutOfBoundsException(index);
}
return Character.codePointBefore(value, index);
} public int codePointCount(int beginIndex, int endIndex) {
if (beginIndex < 0 || endIndex > count || beginIndex > endIndex) {
throw new IndexOutOfBoundsException();
}
return Character.codePointCountImpl(value, beginIndex, endIndex-beginIndex);
} public int offsetByCodePoints(int index, int codePointOffset) {
if (index < 0 || index > count) {
throw new IndexOutOfBoundsException();
}
return Character.offsetByCodePointsImpl(value, 0, count,
index, codePointOffset);
} public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
{
if (srcBegin < 0)
throw new StringIndexOutOfBoundsException(srcBegin);
if ((srcEnd < 0) || (srcEnd > count))
throw new StringIndexOutOfBoundsException(srcEnd);
if (srcBegin > srcEnd)
throw new StringIndexOutOfBoundsException("srcBegin > srcEnd");
System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
} public void setCharAt(int index, char ch) {
if ((index < 0) || (index >= count))
throw new StringIndexOutOfBoundsException(index);
value[index] = ch;
} public AbstractStringBuilder append(Object obj) {
return append(String.valueOf(obj));
} public AbstractStringBuilder append(String str) {
if (str == null) str = "null";
int len = str.length();
ensureCapacityInternal(count + len);
str.getChars(0, len, value, count);
count += len;
return this;
} // Documentation in subclasses because of synchro difference
public AbstractStringBuilder append(StringBuffer sb) {
if (sb == null)
return append("null");
int len = sb.length();
ensureCapacityInternal(count + len);
sb.getChars(0, len, value, count);
count += len;
return this;
} // Documentation in subclasses because of synchro difference
public AbstractStringBuilder append(CharSequence s) {
if (s == null)
s = "null";
if (s instanceof String)
return this.append((String)s);
if (s instanceof StringBuffer)
return this.append((StringBuffer)s);
return this.append(s, 0, s.length());
} public AbstractStringBuilder append(CharSequence s, int start, int end) {
if (s == null)
s = "null";
if ((start < 0) || (start > end) || (end > s.length()))
throw new IndexOutOfBoundsException(
"start " + start + ", end " + end + ", s.length() "
+ s.length());
int len = end - start;
ensureCapacityInternal(count + len);
for (int i = start, j = count; i < end; i++, j++)
value[j] = s.charAt(i);
count += len;
return this;
} public AbstractStringBuilder append(char[] str) {
int len = str.length;
ensureCapacityInternal(count + len);
System.arraycopy(str, 0, value, count, len);
count += len;
return this;
} public AbstractStringBuilder append(char str[], int offset, int len) {
if (len > 0) // let arraycopy report AIOOBE for len < 0
ensureCapacityInternal(count + len);
System.arraycopy(str, offset, value, count, len);
count += len;
return this;
} public AbstractStringBuilder append(boolean b) {
if (b) {
ensureCapacityInternal(count + 4);
value[count++] = 't';
value[count++] = 'r';
value[count++] = 'u';
value[count++] = 'e';
} else {
ensureCapacityInternal(count + 5);
value[count++] = 'f';
value[count++] = 'a';
value[count++] = 'l';
value[count++] = 's';
value[count++] = 'e';
}
return this;
} public AbstractStringBuilder append(char c) {
ensureCapacityInternal(count + 1);
value[count++] = c;
return this;
} public AbstractStringBuilder append(int i) {
if (i == Integer.MIN_VALUE) {
append("-2147483648");
return this;
}
int appendedLength = (i < 0) ? Integer.stringSize(-i) + 1
: Integer.stringSize(i);
int spaceNeeded = count + appendedLength;
ensureCapacityInternal(spaceNeeded);
Integer.getChars(i, spaceNeeded, value);
count = spaceNeeded;
return this;
} public AbstractStringBuilder append(long l) {
if (l == Long.MIN_VALUE) {
append("-9223372036854775808");
return this;
}
int appendedLength = (l < 0) ? Long.stringSize(-l) + 1
: Long.stringSize(l);
int spaceNeeded = count + appendedLength;
ensureCapacityInternal(spaceNeeded);
Long.getChars(l, spaceNeeded, value);
count = spaceNeeded;
return this;
} public AbstractStringBuilder append(float f) {
new FloatingDecimal(f).appendTo(this);
return this;
} public AbstractStringBuilder append(double d) {
new FloatingDecimal(d).appendTo(this);
return this;
} public AbstractStringBuilder delete(int start, int end) {
if (start < 0)
throw new StringIndexOutOfBoundsException(start);
if (end > count)
end = count;
if (start > end)
throw new StringIndexOutOfBoundsException();
int len = end - start;
if (len > 0) {
System.arraycopy(value, start+len, value, start, count-end);
count -= len;
}
return this;
} public AbstractStringBuilder appendCodePoint(int codePoint) {
final int count = this.count; if (Character.isBmpCodePoint(codePoint)) {
ensureCapacityInternal(count + 1);
value[count] = (char) codePoint;
this.count = count + 1;
} else if (Character.isValidCodePoint(codePoint)) {
ensureCapacityInternal(count + 2);
Character.toSurrogates(codePoint, value, count);
this.count = count + 2;
} else {
throw new IllegalArgumentException();
}
return this;
} public AbstractStringBuilder deleteCharAt(int index) {
if ((index < 0) || (index >= count))
throw new StringIndexOutOfBoundsException(index);
System.arraycopy(value, index+1, value, index, count-index-1);
count--;
return this;
} public AbstractStringBuilder replace(int start, int end, String str) {
if (start < 0)
throw new StringIndexOutOfBoundsException(start);
if (start > count)
throw new StringIndexOutOfBoundsException("start > length()");
if (start > end)
throw new StringIndexOutOfBoundsException("start > end"); if (end > count)
end = count;
int len = str.length();
int newCount = count + len - (end - start);
ensureCapacityInternal(newCount); System.arraycopy(value, end, value, start + len, count - end);
str.getChars(value, start);
count = newCount;
return this;
} public String substring(int start) {
return substring(start, count);
} public CharSequence subSequence(int start, int end) {
return substring(start, end);
} public String substring(int start, int end) {
if (start < 0)
throw new StringIndexOutOfBoundsException(start);
if (end > count)
throw new StringIndexOutOfBoundsException(end);
if (start > end)
throw new StringIndexOutOfBoundsException(end - start);
return new String(value, start, end - start);
} public AbstractStringBuilder insert(int index, char[] str, int offset,
int len)
{
if ((index < 0) || (index > length()))
throw new StringIndexOutOfBoundsException(index);
if ((offset < 0) || (len < 0) || (offset > str.length - len))
throw new StringIndexOutOfBoundsException(
"offset " + offset + ", len " + len + ", str.length "
+ str.length);
ensureCapacityInternal(count + len);
System.arraycopy(value, index, value, index + len, count - index);
System.arraycopy(str, offset, value, index, len);
count += len;
return this;
} public AbstractStringBuilder insert(int offset, Object obj) {
return insert(offset, String.valueOf(obj));
} public AbstractStringBuilder insert(int offset, String str) {
if ((offset < 0) || (offset > length()))
throw new StringIndexOutOfBoundsException(offset);
if (str == null)
str = "null";
int len = str.length();
ensureCapacityInternal(count + len);
System.arraycopy(value, offset, value, offset + len, count - offset);
str.getChars(value, offset);
count += len;
return this;
} public AbstractStringBuilder insert(int offset, char[] str) {
if ((offset < 0) || (offset > length()))
throw new StringIndexOutOfBoundsException(offset);
int len = str.length;
ensureCapacityInternal(count + len);
System.arraycopy(value, offset, value, offset + len, count - offset);
System.arraycopy(str, 0, value, offset, len);
count += len;
return this;
} public AbstractStringBuilder insert(int dstOffset, CharSequence s) {
if (s == null)
s = "null";
if (s instanceof String)
return this.insert(dstOffset, (String)s);
return this.insert(dstOffset, s, 0, s.length());
} public AbstractStringBuilder insert(int dstOffset, CharSequence s,
int start, int end) {
if (s == null)
s = "null";
if ((dstOffset < 0) || (dstOffset > this.length()))
throw new IndexOutOfBoundsException("dstOffset "+dstOffset);
if ((start < 0) || (end < 0) || (start > end) || (end > s.length()))
throw new IndexOutOfBoundsException(
"start " + start + ", end " + end + ", s.length() "
+ s.length());
int len = end - start;
ensureCapacityInternal(count + len);
System.arraycopy(value, dstOffset, value, dstOffset + len,
count - dstOffset);
for (int i=start; i<end; i++)
value[dstOffset++] = s.charAt(i);
count += len;
return this;
} public AbstractStringBuilder insert(int offset, boolean b) {
return insert(offset, String.valueOf(b));
} public AbstractStringBuilder insert(int offset, char c) {
ensureCapacityInternal(count + 1);
System.arraycopy(value, offset, value, offset + 1, count - offset);
value[offset] = c;
count += 1;
return this;
} public AbstractStringBuilder insert(int offset, int i) {
return insert(offset, String.valueOf(i));
} public AbstractStringBuilder insert(int offset, long l) {
return insert(offset, String.valueOf(l));
} public AbstractStringBuilder insert(int offset, float f) {
return insert(offset, String.valueOf(f));
} public AbstractStringBuilder insert(int offset, double d) {
return insert(offset, String.valueOf(d));
} public int indexOf(String str) {
return indexOf(str, 0);
} public int indexOf(String str, int fromIndex) {
return String.indexOf(value, 0, count,
str.toCharArray(), 0, str.length(), fromIndex);
} public int lastIndexOf(String str) {
return lastIndexOf(str, count);
} public int lastIndexOf(String str, int fromIndex) {
return String.lastIndexOf(value, 0, count,
str.toCharArray(), 0, str.length(), fromIndex);
} public AbstractStringBuilder reverse() {
boolean hasSurrogate = false;
int n = count - 1;
for (int j = (n-1) >> 1; j >= 0; --j) {
char temp = value[j];
char temp2 = value[n - j];
if (!hasSurrogate) {
hasSurrogate = (temp >= Character.MIN_SURROGATE && temp <= Character.MAX_SURROGATE)
|| (temp2 >= Character.MIN_SURROGATE && temp2 <= Character.MAX_SURROGATE);
}
value[j] = temp2;
value[n - j] = temp;
}
if (hasSurrogate) {
// Reverse back all valid surrogate pairs
for (int i = 0; i < count - 1; i++) {
char c2 = value[i];
if (Character.isLowSurrogate(c2)) {
char c1 = value[i + 1];
if (Character.isHighSurrogate(c1)) {
value[i++] = c1;
value[i] = c2;
}
}
}
}
return this;
} public abstract String toString(); final char[] getValue() {
return value;
}
}
StringBuilder源码(基于jdk1.7.40)
package java.lang; public final class StringBuilder
extends AbstractStringBuilder
implements java.io.Serializable, CharSequence { static final long serialVersionUID = 4383685877147921099L; // 构造函数。默认的字符数组大小是16。
public StringBuilder() {
super(16);
} // 构造函数。指定StringBuilder的字符数组大小是capacity。
public StringBuilder(int capacity) {
super(capacity);
} // 构造函数。指定字符数组大小=str长度+15,且将str的值赋值到当前字符数组中。
public StringBuilder(String str) {
super(str.length() + 16);
append(str);
} // 构造函数。指定字符数组大小=seq长度+15,且将seq的值赋值到当前字符数组中。
public StringBuilder(CharSequence seq) {
this(seq.length() + 16);
append(seq);
} // 追加“对象obj对应的字符串”。String.valueOf(obj)实际上是调用obj.toString()
public StringBuilder append(Object obj) {
return append(String.valueOf(obj));
} // 追加“str”。
public StringBuilder append(String str) {
super.append(str);
return this;
} // 追加“sb的内容”。
private StringBuilder append(StringBuilder sb) {
if (sb == null)
return append("null");
int len = sb.length();
int newcount = count + len;
if (newcount > value.length)
expandCapacity(newcount);
sb.getChars(0, len, value, count);
count = newcount;
return this;
} // 追加“sb的内容”。
public StringBuilder append(StringBuffer sb) {
super.append(sb);
return this;
} // 追加“s的内容”。
public StringBuilder append(CharSequence s) {
if (s == null)
s = "null";
if (s instanceof String)
return this.append((String)s);
if (s instanceof StringBuffer)
return this.append((StringBuffer)s);
if (s instanceof StringBuilder)
return this.append((StringBuilder)s);
return this.append(s, 0, s.length());
} // 追加“s从start(包括)到end(不包括)的内容”。
public StringBuilder append(CharSequence s, int start, int end) {
super.append(s, start, end);
return this;
} // 追加“str字符数组对应的字符串”
public StringBuilder append(char[] str) {
super.append(str);
return this;
} // 追加“str从offset开始的内容,内容长度是len”
public StringBuilder append(char[] str, int offset, int len) {
super.append(str, offset, len);
return this;
} // 追加“b对应的字符串”
public StringBuilder append(boolean b) {
super.append(b);
return this;
} // 追加“c”
public StringBuilder append(char c) {
super.append(c);
return this;
} // 追加“i”
public StringBuilder append(int i) {
super.append(i);
return this;
} // 追加“lng”
public StringBuilder append(long lng) {
super.append(lng);
return this;
} // 追加“f”
public StringBuilder append(float f) {
super.append(f);
return this;
} // 追加“d”
public StringBuilder append(double d) {
super.append(d);
return this;
} // 追加“codePoint”
public StringBuilder appendCodePoint(int codePoint) {
super.appendCodePoint(codePoint);
return this;
} // 删除“从start(包括)到end的内容”
public StringBuilder delete(int start, int end) {
super.delete(start, end);
return this;
} // 删除“位置index的内容”
public StringBuilder deleteCharAt(int index) {
super.deleteCharAt(index);
return this;
} // “用str替换StringBuilder中从start(包括)到end(不包括)的内容”
public StringBuilder replace(int start, int end, String str) {
super.replace(start, end, str);
return this;
} // “在StringBuilder的位置index处插入‘str中从offset开始的内容’,插入内容长度是len”
public StringBuilder insert(int index, char[] str, int offset,
int len)
{
super.insert(index, str, offset, len);
return this;
} // “在StringBuilder的位置offset处插入obj对应的字符串”
public StringBuilder insert(int offset, Object obj) {
return insert(offset, String.valueOf(obj));
} // “在StringBuilder的位置offset处插入str”
public StringBuilder insert(int offset, String str) {
super.insert(offset, str);
return this;
} // “在StringBuilder的位置offset处插入str”
public StringBuilder insert(int offset, char[] str) {
super.insert(offset, str);
return this;
} // “在StringBuilder的位置dstOffset处插入s”
public StringBuilder insert(int dstOffset, CharSequence s) {
if (s == null)
s = "null";
if (s instanceof String)
return this.insert(dstOffset, (String)s);
return this.insert(dstOffset, s, 0, s.length());
} // “在StringBuilder的位置dstOffset处插入's中从start到end的内容'”
public StringBuilder insert(int dstOffset, CharSequence s,
int start, int end)
{
super.insert(dstOffset, s, start, end);
return this;
} // “在StringBuilder的位置Offset处插入b”
public StringBuilder insert(int offset, boolean b) {
super.insert(offset, b);
return this;
} // “在StringBuilder的位置Offset处插入c”
public StringBuilder insert(int offset, char c) {
super.insert(offset, c);
return this;
} // “在StringBuilder的位置Offset处插入i”
public StringBuilder insert(int offset, int i) {
return insert(offset, String.valueOf(i));
} // “在StringBuilder的位置Offset处插入l”
public StringBuilder insert(int offset, long l) {
return insert(offset, String.valueOf(l));
} // “在StringBuilder的位置Offset处插入f”
public StringBuilder insert(int offset, float f) {
return insert(offset, String.valueOf(f));
} // “在StringBuilder的位置Offset处插入d”
public StringBuilder insert(int offset, double d) {
return insert(offset, String.valueOf(d));
} // 返回“str”在StringBuilder的位置
public int indexOf(String str) {
return indexOf(str, 0);
} // 从fromIndex开始查找,返回“str”在StringBuilder的位置
public int indexOf(String str, int fromIndex) {
return String.indexOf(value, 0, count,
str.toCharArray(), 0, str.length(), fromIndex);
} // 从后向前查找,返回“str”在StringBuilder的位置
public int lastIndexOf(String str) {
return lastIndexOf(str, count);
} // 从fromIndex开始,从后向前查找,返回“str”在StringBuilder的位置
public int lastIndexOf(String str, int fromIndex) {
return String.lastIndexOf(value, 0, count,
str.toCharArray(), 0, str.length(), fromIndex);
} // 反转StringBuilder
public StringBuilder reverse() {
super.reverse();
return this;
} public String toString() {
// Create a copy, don't share the array
return new String(value, 0, count);
} // 序列化对应的写入函数
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
s.defaultWriteObject();
s.writeInt(count);
s.writeObject(value);
} // 序列化对应的读取函数
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
count = s.readInt();
value = (char[]) s.readObject();
}
}
1. StringBuilder 中插入(insert)相关的API
源码如下(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(); // 在位置0处插入字符数组
sbuilder.insert(0, new char[]{'a','b','c','d','e'});
// 在位置0处插入字符数组。0表示字符数组起始位置,3表示长度
sbuilder.insert(0, new char[]{'A','B','C','D','E'}, 0, 3);
// 在位置0处插入float
sbuilder.insert(0, 1.414f);
// 在位置0处插入double
sbuilder.insert(0, 3.14159d);
// 在位置0处插入boolean
sbuilder.insert(0, true);
// 在位置0处插入char
sbuilder.insert(0, '\n');
// 在位置0处插入int
sbuilder.insert(0, 100);
// 在位置0处插入long
sbuilder.insert(0, 12345L);
// 在位置0处插入StringBuilder对象
sbuilder.insert(0, new StringBuilder("StringBuilder"));
// 在位置0处插入StringBuilder对象。6表示被在位置0处插入对象的起始位置(包括),13是结束位置(不包括)
sbuilder.insert(0, new StringBuilder("STRINGBUILDER"), 6, 13);
// 在位置0处插入StringBuffer对象。
sbuilder.insert(0, new StringBuffer("StringBuffer"));
// 在位置0处插入StringBuffer对象。6表示被在位置0处插入对象的起始位置(包括),12是结束位置(不包括)
sbuilder.insert(0, new StringBuffer("STRINGBUFFER"), 6, 12);
// 在位置0处插入String对象。
sbuilder.insert(0, "String");
// 在位置0处插入String对象。1表示被在位置0处插入对象的起始位置(包括),6是结束位置(不包括)
sbuilder.insert(0, "0123456789", 1, 6);
sbuilder.insert(0, '\n'); // 在位置0处插入Object对象。此处以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);
}
}
运行结果:
-------------------------------- testInsertAPIs -------------------------------
{3=three, 2=two, 1=one}
12345StringBUFFERStringBufferBUILDERStringBuilder12345100
true3.141591.414ABCabcde
2. StringBuilder 中追加(append)相关的API
源码如下(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(); // 追加字符数组
sbuilder.append(new char[]{'a','b','c','d','e'});
// 追加字符数组。0表示字符数组起始位置,3表示长度
sbuilder.append(new char[]{'A','B','C','D','E'}, 0, 3);
// 追加float
sbuilder.append(1.414f);
// 追加double
sbuilder.append(3.14159d);
// 追加boolean
sbuilder.append(true);
// 追加char
sbuilder.append('\n');
// 追加int
sbuilder.append(100);
// 追加long
sbuilder.append(12345L);
// 追加StringBuilder对象
sbuilder.append(new StringBuilder("StringBuilder"));
// 追加StringBuilder对象。6表示被追加对象的起始位置(包括),13是结束位置(不包括)
sbuilder.append(new StringBuilder("STRINGBUILDER"), 6, 13);
// 追加StringBuffer对象。
sbuilder.append(new StringBuffer("StringBuffer"));
// 追加StringBuffer对象。6表示被追加对象的起始位置(包括),12是结束位置(不包括)
sbuilder.append(new StringBuffer("STRINGBUFFER"), 6, 12);
// 追加String对象。
sbuilder.append("String");
// 追加String对象。1表示被追加对象的起始位置(包括),6是结束位置(不包括)
sbuilder.append("0123456789", 1, 6);
sbuilder.append('\n'); // 追加Object对象。此处以HashMap为例
HashMap map = new HashMap();
map.put("1", "one");
map.put("2", "two");
map.put("3", "three");
sbuilder.append(map);
sbuilder.append('\n'); // 追加unicode编码
sbuilder.appendCodePoint(0x5b57); // 0x5b57是“字”的unicode编码
sbuilder.appendCodePoint(0x7b26); // 0x7b26是“符”的unicode编码
sbuilder.appendCodePoint(0x7f16); // 0x7f16是“编”的unicode编码
sbuilder.appendCodePoint(0x7801); // 0x7801是“码”的unicode编码 System.out.printf("%s\n\n", sbuilder);
}
}
运行结果:
-------------------------------- testAppendAPIs -------------------------------
abcdeABC1.4143.14159true
10012345StringBuilderBUILDERStringBufferBUFFERString12345
{3=three, 2=two, 1=one}
字符编码
3. StringBuilder 中替换(replace)相关的API
源码如下(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();
}
}
运行结果:
-------------------------------- testReplaceAPIs ------------------------------
sbuilder=ABCDE3456789
sbuilder=9876543210
sbuilder=M123456789
4. StringBuilder 中删除(delete)相关的API
源码如下(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"); // 删除位置0的字符,剩余字符是“123456789”。
sbuilder.deleteCharAt(0);
// 删除位置3(包括)到位置6(不包括)之间的字符,剩余字符是“123789”。
sbuilder.delete(3,6); // 获取sb中从位置1开始的字符串
String str1 = sbuilder.substring(1);
// 获取sb中从位置3(包括)到位置5(不包括)之间的字符串
String str2 = sbuilder.substring(3, 5);
// 获取sb中从位置3(包括)到位置5(不包括)之间的字符串,获取的对象是CharSequence对象,此处转型为String
String str3 = (String)sbuilder.subSequence(3, 5); System.out.printf("sbuilder=%s\nstr1=%s\nstr2=%s\nstr3=%s\n",
sbuilder, str1, str2, str3);
}
}
运行结果:
-------------------------------- testDeleteAPIs -------------------------------
sbuilder=123789
str1=23789
str2=78
str3=78
5. StringBuilder 中index相关的API
源码如下(StringBuilderIndexTest.java):
/**
* StringBuilder 中index相关API演示
*
* @author skywang
*/
import java.util.HashMap; public class StringBuilderIndexTest { public static void main(String[] args) {
testIndexAPIs() ;
} /**
* StringBuilder 中index相关API演示
*/
private static void testIndexAPIs() {
System.out.println("-------------------------------- testIndexAPIs --------------------------------"); StringBuilder sbuilder = new StringBuilder("abcAbcABCabCaBcAbCaBCabc");
System.out.printf("sbuilder=%s\n", sbuilder); // 1. 从前往后,找出"bc"第一次出现的位置
System.out.printf("%-30s = %d\n", "sbuilder.indexOf(\"bc\")", sbuilder.indexOf("bc")); // 2. 从位置5开始,从前往后,找出"bc"第一次出现的位置
System.out.printf("%-30s = %d\n", "sbuilder.indexOf(\"bc\", 5)", sbuilder.indexOf("bc", 5)); // 3. 从后往前,找出"bc"第一次出现的位置
System.out.printf("%-30s = %d\n", "sbuilder.lastIndexOf(\"bc\")", sbuilder.lastIndexOf("bc")); // 4. 从位置4开始,从后往前,找出"bc"第一次出现的位置
System.out.printf("%-30s = %d\n", "sbuilder.lastIndexOf(\"bc\", 4)", sbuilder.lastIndexOf("bc", 4)); System.out.println();
}
}
运行结果:
-------------------------------- testIndexAPIs --------------------------------
sbuilder=abcAbcABCabCaBcAbCaBCabc
sbuilder.indexOf("bc") = 1
sbuilder.indexOf("bc", 5) = 22
sbuilder.lastIndexOf("bc") = 22
sbuilder.lastIndexOf("bc", 4) = 4
6. StringBuilder 剩余的API
源码如下(StringBuilderOtherTest.java):
/**
* StringBuilder 的其它API示例
*
* @author skywang
*/
import java.util.HashMap; public class StringBuilderOtherTest { public static void main(String[] args) {
testOtherAPIs() ;
} /**
* 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<carr.length; i++)
System.out.printf("carr[%d]=%c ", i, carr[i]);
System.out.println(); System.out.println();
}
}
运行结果:
-------------------------------- testOtherAPIs --------------------------------
cap=26
c=6
carr[0]=3 carr[1]=4 carr[2]=5 carr[3]=6
7. StringBuilder 完整示例
下面的示例是整合上面的几个示例的完整的StringBuilder演示程序,源码如下(StringBuilderTest.java):
/**
* StringBuilder 演示程序
*
* @author skywang
*/
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<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. 从前往后,找出"bc"第一次出现的位置
System.out.printf("%-30s = %d\n", "sbuilder.indexOf(\"bc\")", sbuilder.indexOf("bc")); // 2. 从位置5开始,从前往后,找出"bc"第一次出现的位置
System.out.printf("%-30s = %d\n", "sbuilder.indexOf(\"bc\", 5)", sbuilder.indexOf("bc", 5)); // 3. 从后往前,找出"bc"第一次出现的位置
System.out.printf("%-30s = %d\n", "sbuilder.lastIndexOf(\"bc\")", sbuilder.lastIndexOf("bc")); // 4. 从位置4开始,从后往前,找出"bc"第一次出现的位置
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()示例
*/
private static void testDeleteAPIs() { System.out.println("-------------------------------- testDeleteAPIs -------------------------------"); StringBuilder sbuilder = new StringBuilder("0123456789"); // 删除位置0的字符,剩余字符是“123456789”。
sbuilder.deleteCharAt(0);
// 删除位置3(包括)到位置6(不包括)之间的字符,剩余字符是“123789”。
sbuilder.delete(3,6); // 获取sb中从位置1开始的字符串
String str1 = sbuilder.substring(1);
// 获取sb中从位置3(包括)到位置5(不包括)之间的字符串
String str2 = sbuilder.substring(3, 5);
// 获取sb中从位置3(包括)到位置5(不包括)之间的字符串,获取的对象是CharSequence对象,此处转型为String
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()示例
*/
private static void testInsertAPIs() { System.out.println("-------------------------------- testInsertAPIs -------------------------------"); StringBuilder sbuilder = new StringBuilder(); // 在位置0处插入字符数组
sbuilder.insert(0, new char[]{'a','b','c','d','e'});
// 在位置0处插入字符数组。0表示字符数组起始位置,3表示长度
sbuilder.insert(0, new char[]{'A','B','C','D','E'}, 0, 3);
// 在位置0处插入float
sbuilder.insert(0, 1.414f);
// 在位置0处插入double
sbuilder.insert(0, 3.14159d);
// 在位置0处插入boolean
sbuilder.insert(0, true);
// 在位置0处插入char
sbuilder.insert(0, '\n');
// 在位置0处插入int
sbuilder.insert(0, 100);
// 在位置0处插入long
sbuilder.insert(0, 12345L);
// 在位置0处插入StringBuilder对象
sbuilder.insert(0, new StringBuilder("StringBuilder"));
// 在位置0处插入StringBuilder对象。6表示被在位置0处插入对象的起始位置(包括),13是结束位置(不包括)
sbuilder.insert(0, new StringBuilder("STRINGBUILDER"), 6, 13);
// 在位置0处插入StringBuffer对象。
sbuilder.insert(0, new StringBuffer("StringBuffer"));
// 在位置0处插入StringBuffer对象。6表示被在位置0处插入对象的起始位置(包括),12是结束位置(不包括)
sbuilder.insert(0, new StringBuffer("STRINGBUFFER"), 6, 12);
// 在位置0处插入String对象。
sbuilder.insert(0, "String");
// 在位置0处插入String对象。1表示被在位置0处插入对象的起始位置(包括),6是结束位置(不包括)
sbuilder.insert(0, "0123456789", 1, 6);
sbuilder.insert(0, '\n'); // 在位置0处插入Object对象。此处以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(); // 追加字符数组
sbuilder.append(new char[]{'a','b','c','d','e'});
// 追加字符数组。0表示字符数组起始位置,3表示长度
sbuilder.append(new char[]{'A','B','C','D','E'}, 0, 3);
// 追加float
sbuilder.append(1.414f);
// 追加double
sbuilder.append(3.14159d);
// 追加boolean
sbuilder.append(true);
// 追加char
sbuilder.append('\n');
// 追加int
sbuilder.append(100);
// 追加long
sbuilder.append(12345L);
// 追加StringBuilder对象
sbuilder.append(new StringBuilder("StringBuilder"));
// 追加StringBuilder对象。6表示被追加对象的起始位置(包括),13是结束位置(不包括)
sbuilder.append(new StringBuilder("STRINGBUILDER"), 6, 13);
// 追加StringBuffer对象。
sbuilder.append(new StringBuffer("StringBuffer"));
// 追加StringBuffer对象。6表示被追加对象的起始位置(包括),12是结束位置(不包括)
sbuilder.append(new StringBuffer("STRINGBUFFER"), 6, 12);
// 追加String对象。
sbuilder.append("String");
// 追加String对象。1表示被追加对象的起始位置(包括),6是结束位置(不包括)
sbuilder.append("0123456789", 1, 6);
sbuilder.append('\n'); // 追加Object对象。此处以HashMap为例
HashMap map = new HashMap();
map.put("1", "one");
map.put("2", "two");
map.put("3", "three");
sbuilder.append(map);
sbuilder.append('\n'); // 追加unicode编码
sbuilder.appendCodePoint(0x5b57); // 0x5b57是“字”的unicode编码
sbuilder.appendCodePoint(0x7b26); // 0x7b26是“符”的unicode编码
sbuilder.appendCodePoint(0x7f16); // 0x7f16是“编”的unicode编码
sbuilder.appendCodePoint(0x7801); // 0x7801是“码”的unicode编码 System.out.printf("%s\n\n", sbuilder);
}
}