本章介绍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)
1 package java.lang; 2 3 import sun.misc.FloatingDecimal; 4 import java.util.Arrays; 5 6 abstract class AbstractStringBuilder implements Appendable, CharSequence { 7 char[] value; 8 9 int count; 10 11 AbstractStringBuilder() { 12 } 13 14 AbstractStringBuilder(int capacity) { 15 value = new char[capacity]; 16 } 17 18 public int length() { 19 return count; 20 } 21 22 public int capacity() { 23 return value.length; 24 } 25 26 public void ensureCapacity(int minimumCapacity) { 27 if (minimumCapacity > 0) 28 ensureCapacityInternal(minimumCapacity); 29 } 30 31 private void ensureCapacityInternal(int minimumCapacity) { 32 // overflow-conscious code 33 if (minimumCapacity - value.length > 0) 34 expandCapacity(minimumCapacity); 35 } 36 37 void expandCapacity(int minimumCapacity) { 38 int newCapacity = value.length * 2 + 2; 39 if (newCapacity - minimumCapacity < 0) 40 newCapacity = minimumCapacity; 41 if (newCapacity < 0) { 42 if (minimumCapacity < 0) // overflow 43 throw new OutOfMemoryError(); 44 newCapacity = Integer.MAX_VALUE; 45 } 46 value = Arrays.copyOf(value, newCapacity); 47 } 48 49 public void trimToSize() { 50 if (count < value.length) { 51 value = Arrays.copyOf(value, count); 52 } 53 } 54 55 public void setLength(int newLength) { 56 if (newLength < 0) 57 throw new StringIndexOutOfBoundsException(newLength); 58 ensureCapacityInternal(newLength); 59 60 if (count < newLength) { 61 for (; count < newLength; count++) 62 value[count] = '\0'; 63 } else { 64 count = newLength; 65 } 66 } 67 68 public char charAt(int index) { 69 if ((index < 0) || (index >= count)) 70 throw new StringIndexOutOfBoundsException(index); 71 return value[index]; 72 } 73 74 public int codePointAt(int index) { 75 if ((index < 0) || (index >= count)) { 76 throw new StringIndexOutOfBoundsException(index); 77 } 78 return Character.codePointAt(value, index); 79 } 80 81 public int codePointBefore(int index) { 82 int i = index - 1; 83 if ((i < 0) || (i >= count)) { 84 throw new StringIndexOutOfBoundsException(index); 85 } 86 return Character.codePointBefore(value, index); 87 } 88 89 public int codePointCount(int beginIndex, int endIndex) { 90 if (beginIndex < 0 || endIndex > count || beginIndex > endIndex) { 91 throw new IndexOutOfBoundsException(); 92 } 93 return Character.codePointCountImpl(value, beginIndex, endIndex-beginIndex); 94 } 95 96 public int offsetByCodePoints(int index, int codePointOffset) { 97 if (index < 0 || index > count) { 98 throw new IndexOutOfBoundsException(); 99 } 100 return Character.offsetByCodePointsImpl(value, 0, count, 101 index, codePointOffset); 102 } 103 104 public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) 105 { 106 if (srcBegin < 0) 107 throw new StringIndexOutOfBoundsException(srcBegin); 108 if ((srcEnd < 0) || (srcEnd > count)) 109 throw new StringIndexOutOfBoundsException(srcEnd); 110 if (srcBegin > srcEnd) 111 throw new StringIndexOutOfBoundsException("srcBegin > srcEnd"); 112 System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin); 113 } 114 115 public void setCharAt(int index, char ch) { 116 if ((index < 0) || (index >= count)) 117 throw new StringIndexOutOfBoundsException(index); 118 value[index] = ch; 119 } 120 121 public AbstractStringBuilder append(Object obj) { 122 return append(String.valueOf(obj)); 123 } 124 125 public AbstractStringBuilder append(String str) { 126 if (str == null) str = "null"; 127 int len = str.length(); 128 ensureCapacityInternal(count + len); 129 str.getChars(0, len, value, count); 130 count += len; 131 return this; 132 } 133 134 // Documentation in subclasses because of synchro difference 135 public AbstractStringBuilder append(StringBuffer sb) { 136 if (sb == null) 137 return append("null"); 138 int len = sb.length(); 139 ensureCapacityInternal(count + len); 140 sb.getChars(0, len, value, count); 141 count += len; 142 return this; 143 } 144 145 // Documentation in subclasses because of synchro difference 146 public AbstractStringBuilder append(CharSequence s) { 147 if (s == null) 148 s = "null"; 149 if (s instanceof String) 150 return this.append((String)s); 151 if (s instanceof StringBuffer) 152 return this.append((StringBuffer)s); 153 return this.append(s, 0, s.length()); 154 } 155 156 public AbstractStringBuilder append(CharSequence s, int start, int end) { 157 if (s == null) 158 s = "null"; 159 if ((start < 0) || (start > end) || (end > s.length())) 160 throw new IndexOutOfBoundsException( 161 "start " + start + ", end " + end + ", s.length() " 162 + s.length()); 163 int len = end - start; 164 ensureCapacityInternal(count + len); 165 for (int i = start, j = count; i < end; i++, j++) 166 value[j] = s.charAt(i); 167 count += len; 168 return this; 169 } 170 171 public AbstractStringBuilder append(char[] str) { 172 int len = str.length; 173 ensureCapacityInternal(count + len); 174 System.arraycopy(str, 0, value, count, len); 175 count += len; 176 return this; 177 } 178 179 public AbstractStringBuilder append(char str[], int offset, int len) { 180 if (len > 0) // let arraycopy report AIOOBE for len < 0 181 ensureCapacityInternal(count + len); 182 System.arraycopy(str, offset, value, count, len); 183 count += len; 184 return this; 185 } 186 187 public AbstractStringBuilder append(boolean b) { 188 if (b) { 189 ensureCapacityInternal(count + 4); 190 value[count++] = 't'; 191 value[count++] = 'r'; 192 value[count++] = 'u'; 193 value[count++] = 'e'; 194 } else { 195 ensureCapacityInternal(count + 5); 196 value[count++] = 'f'; 197 value[count++] = 'a'; 198 value[count++] = 'l'; 199 value[count++] = 's'; 200 value[count++] = 'e'; 201 } 202 return this; 203 } 204 205 public AbstractStringBuilder append(char c) { 206 ensureCapacityInternal(count + 1); 207 value[count++] = c; 208 return this; 209 } 210 211 public AbstractStringBuilder append(int i) { 212 if (i == Integer.MIN_VALUE) { 213 append("-2147483648"); 214 return this; 215 } 216 int appendedLength = (i < 0) ? Integer.stringSize(-i) + 1 217 : Integer.stringSize(i); 218 int spaceNeeded = count + appendedLength; 219 ensureCapacityInternal(spaceNeeded); 220 Integer.getChars(i, spaceNeeded, value); 221 count = spaceNeeded; 222 return this; 223 } 224 225 public AbstractStringBuilder append(long l) { 226 if (l == Long.MIN_VALUE) { 227 append("-9223372036854775808"); 228 return this; 229 } 230 int appendedLength = (l < 0) ? Long.stringSize(-l) + 1 231 : Long.stringSize(l); 232 int spaceNeeded = count + appendedLength; 233 ensureCapacityInternal(spaceNeeded); 234 Long.getChars(l, spaceNeeded, value); 235 count = spaceNeeded; 236 return this; 237 } 238 239 public AbstractStringBuilder append(float f) { 240 new FloatingDecimal(f).appendTo(this); 241 return this; 242 } 243 244 public AbstractStringBuilder append(double d) { 245 new FloatingDecimal(d).appendTo(this); 246 return this; 247 } 248 249 public AbstractStringBuilder delete(int start, int end) { 250 if (start < 0) 251 throw new StringIndexOutOfBoundsException(start); 252 if (end > count) 253 end = count; 254 if (start > end) 255 throw new StringIndexOutOfBoundsException(); 256 int len = end - start; 257 if (len > 0) { 258 System.arraycopy(value, start+len, value, start, count-end); 259 count -= len; 260 } 261 return this; 262 } 263 264 public AbstractStringBuilder appendCodePoint(int codePoint) { 265 final int count = this.count; 266 267 if (Character.isBmpCodePoint(codePoint)) { 268 ensureCapacityInternal(count + 1); 269 value[count] = (char) codePoint; 270 this.count = count + 1; 271 } else if (Character.isValidCodePoint(codePoint)) { 272 ensureCapacityInternal(count + 2); 273 Character.toSurrogates(codePoint, value, count); 274 this.count = count + 2; 275 } else { 276 throw new IllegalArgumentException(); 277 } 278 return this; 279 } 280 281 public AbstractStringBuilder deleteCharAt(int index) { 282 if ((index < 0) || (index >= count)) 283 throw new StringIndexOutOfBoundsException(index); 284 System.arraycopy(value, index+1, value, index, count-index-1); 285 count--; 286 return this; 287 } 288 289 public AbstractStringBuilder replace(int start, int end, String str) { 290 if (start < 0) 291 throw new StringIndexOutOfBoundsException(start); 292 if (start > count) 293 throw new StringIndexOutOfBoundsException("start > length()"); 294 if (start > end) 295 throw new StringIndexOutOfBoundsException("start > end"); 296 297 if (end > count) 298 end = count; 299 int len = str.length(); 300 int newCount = count + len - (end - start); 301 ensureCapacityInternal(newCount); 302 303 System.arraycopy(value, end, value, start + len, count - end); 304 str.getChars(value, start); 305 count = newCount; 306 return this; 307 } 308 309 public String substring(int start) { 310 return substring(start, count); 311 } 312 313 public CharSequence subSequence(int start, int end) { 314 return substring(start, end); 315 } 316 317 public String substring(int start, int end) { 318 if (start < 0) 319 throw new StringIndexOutOfBoundsException(start); 320 if (end > count) 321 throw new StringIndexOutOfBoundsException(end); 322 if (start > end) 323 throw new StringIndexOutOfBoundsException(end - start); 324 return new String(value, start, end - start); 325 } 326 327 public AbstractStringBuilder insert(int index, char[] str, int offset, 328 int len) 329 { 330 if ((index < 0) || (index > length())) 331 throw new StringIndexOutOfBoundsException(index); 332 if ((offset < 0) || (len < 0) || (offset > str.length - len)) 333 throw new StringIndexOutOfBoundsException( 334 "offset " + offset + ", len " + len + ", str.length " 335 + str.length); 336 ensureCapacityInternal(count + len); 337 System.arraycopy(value, index, value, index + len, count - index); 338 System.arraycopy(str, offset, value, index, len); 339 count += len; 340 return this; 341 } 342 343 public AbstractStringBuilder insert(int offset, Object obj) { 344 return insert(offset, String.valueOf(obj)); 345 } 346 347 public AbstractStringBuilder insert(int offset, String str) { 348 if ((offset < 0) || (offset > length())) 349 throw new StringIndexOutOfBoundsException(offset); 350 if (str == null) 351 str = "null"; 352 int len = str.length(); 353 ensureCapacityInternal(count + len); 354 System.arraycopy(value, offset, value, offset + len, count - offset); 355 str.getChars(value, offset); 356 count += len; 357 return this; 358 } 359 360 public AbstractStringBuilder insert(int offset, char[] str) { 361 if ((offset < 0) || (offset > length())) 362 throw new StringIndexOutOfBoundsException(offset); 363 int len = str.length; 364 ensureCapacityInternal(count + len); 365 System.arraycopy(value, offset, value, offset + len, count - offset); 366 System.arraycopy(str, 0, value, offset, len); 367 count += len; 368 return this; 369 } 370 371 public AbstractStringBuilder insert(int dstOffset, CharSequence s) { 372 if (s == null) 373 s = "null"; 374 if (s instanceof String) 375 return this.insert(dstOffset, (String)s); 376 return this.insert(dstOffset, s, 0, s.length()); 377 } 378 379 public AbstractStringBuilder insert(int dstOffset, CharSequence s, 380 int start, int end) { 381 if (s == null) 382 s = "null"; 383 if ((dstOffset < 0) || (dstOffset > this.length())) 384 throw new IndexOutOfBoundsException("dstOffset "+dstOffset); 385 if ((start < 0) || (end < 0) || (start > end) || (end > s.length())) 386 throw new IndexOutOfBoundsException( 387 "start " + start + ", end " + end + ", s.length() " 388 + s.length()); 389 int len = end - start; 390 ensureCapacityInternal(count + len); 391 System.arraycopy(value, dstOffset, value, dstOffset + len, 392 count - dstOffset); 393 for (int i=start; i<end; i++) 394 value[dstOffset++] = s.charAt(i); 395 count += len; 396 return this; 397 } 398 399 public AbstractStringBuilder insert(int offset, boolean b) { 400 return insert(offset, String.valueOf(b)); 401 } 402 403 public AbstractStringBuilder insert(int offset, char c) { 404 ensureCapacityInternal(count + 1); 405 System.arraycopy(value, offset, value, offset + 1, count - offset); 406 value[offset] = c; 407 count += 1; 408 return this; 409 } 410 411 public AbstractStringBuilder insert(int offset, int i) { 412 return insert(offset, String.valueOf(i)); 413 } 414 415 public AbstractStringBuilder insert(int offset, long l) { 416 return insert(offset, String.valueOf(l)); 417 } 418 419 public AbstractStringBuilder insert(int offset, float f) { 420 return insert(offset, String.valueOf(f)); 421 } 422 423 public AbstractStringBuilder insert(int offset, double d) { 424 return insert(offset, String.valueOf(d)); 425 } 426 427 public int indexOf(String str) { 428 return indexOf(str, 0); 429 } 430 431 public int indexOf(String str, int fromIndex) { 432 return String.indexOf(value, 0, count, 433 str.toCharArray(), 0, str.length(), fromIndex); 434 } 435 436 public int lastIndexOf(String str) { 437 return lastIndexOf(str, count); 438 } 439 440 public int lastIndexOf(String str, int fromIndex) { 441 return String.lastIndexOf(value, 0, count, 442 str.toCharArray(), 0, str.length(), fromIndex); 443 } 444 445 public AbstractStringBuilder reverse() { 446 boolean hasSurrogate = false; 447 int n = count - 1; 448 for (int j = (n-1) >> 1; j >= 0; --j) { 449 char temp = value[j]; 450 char temp2 = value[n - j]; 451 if (!hasSurrogate) { 452 hasSurrogate = (temp >= Character.MIN_SURROGATE && temp <= Character.MAX_SURROGATE) 453 || (temp2 >= Character.MIN_SURROGATE && temp2 <= Character.MAX_SURROGATE); 454 } 455 value[j] = temp2; 456 value[n - j] = temp; 457 } 458 if (hasSurrogate) { 459 // Reverse back all valid surrogate pairs 460 for (int i = 0; i < count - 1; i++) { 461 char c2 = value[i]; 462 if (Character.isLowSurrogate(c2)) { 463 char c1 = value[i + 1]; 464 if (Character.isHighSurrogate(c1)) { 465 value[i++] = c1; 466 value[i] = c2; 467 } 468 } 469 } 470 } 471 return this; 472 } 473 474 public abstract String toString(); 475 476 final char[] getValue() { 477 return value; 478 } 479 }
StringBuilder源码(基于jdk1.7.40)
1 package java.lang; 2 3 public final class StringBuilder 4 extends AbstractStringBuilder 5 implements java.io.Serializable, CharSequence { 6 7 static final long serialVersionUID = 4383685877147921099L; 8 9 // 构造函数。默认的字符数组大小是16。 10 public StringBuilder() { 11 super(16); 12 } 13 14 // 构造函数。指定StringBuilder的字符数组大小是capacity。 15 public StringBuilder(int capacity) { 16 super(capacity); 17 } 18 19 // 构造函数。指定字符数组大小=str长度+15,且将str的值赋值到当前字符数组中。 20 public StringBuilder(String str) { 21 super(str.length() + 16); 22 append(str); 23 } 24 25 // 构造函数。指定字符数组大小=seq长度+15,且将seq的值赋值到当前字符数组中。 26 public StringBuilder(CharSequence seq) { 27 this(seq.length() + 16); 28 append(seq); 29 } 30 31 // 追加“对象obj对应的字符串”。String.valueOf(obj)实际上是调用obj.toString() 32 public StringBuilder append(Object obj) { 33 return append(String.valueOf(obj)); 34 } 35 36 // 追加“str”。 37 public StringBuilder append(String str) { 38 super.append(str); 39 return this; 40 } 41 42 // 追加“sb的内容”。 43 private StringBuilder append(StringBuilder sb) { 44 if (sb == null) 45 return append("null"); 46 int len = sb.length(); 47 int newcount = count + len; 48 if (newcount > value.length) 49 expandCapacity(newcount); 50 sb.getChars(0, len, value, count); 51 count = newcount; 52 return this; 53 } 54 55 // 追加“sb的内容”。 56 public StringBuilder append(StringBuffer sb) { 57 super.append(sb); 58 return this; 59 } 60 61 // 追加“s的内容”。 62 public StringBuilder append(CharSequence s) { 63 if (s == null) 64 s = "null"; 65 if (s instanceof String) 66 return this.append((String)s); 67 if (s instanceof StringBuffer) 68 return this.append((StringBuffer)s); 69 if (s instanceof StringBuilder) 70 return this.append((StringBuilder)s); 71 return this.append(s, 0, s.length()); 72 } 73 74 // 追加“s从start(包括)到end(不包括)的内容”。 75 public StringBuilder append(CharSequence s, int start, int end) { 76 super.append(s, start, end); 77 return this; 78 } 79 80 // 追加“str字符数组对应的字符串” 81 public StringBuilder append(char[] str) { 82 super.append(str); 83 return this; 84 } 85 86 // 追加“str从offset开始的内容,内容长度是len” 87 public StringBuilder append(char[] str, int offset, int len) { 88 super.append(str, offset, len); 89 return this; 90 } 91 92 // 追加“b对应的字符串” 93 public StringBuilder append(boolean b) { 94 super.append(b); 95 return this; 96 } 97 98 // 追加“c” 99 public StringBuilder append(char c) { 100 super.append(c); 101 return this; 102 } 103 104 // 追加“i” 105 public StringBuilder append(int i) { 106 super.append(i); 107 return this; 108 } 109 110 // 追加“lng” 111 public StringBuilder append(long lng) { 112 super.append(lng); 113 return this; 114 } 115 116 // 追加“f” 117 public StringBuilder append(float f) { 118 super.append(f); 119 return this; 120 } 121 122 // 追加“d” 123 public StringBuilder append(double d) { 124 super.append(d); 125 return this; 126 } 127 128 // 追加“codePoint” 129 public StringBuilder appendCodePoint(int codePoint) { 130 super.appendCodePoint(codePoint); 131 return this; 132 } 133 134 // 删除“从start(包括)到end的内容” 135 public StringBuilder delete(int start, int end) { 136 super.delete(start, end); 137 return this; 138 } 139 140 // 删除“位置index的内容” 141 public StringBuilder deleteCharAt(int index) { 142 super.deleteCharAt(index); 143 return this; 144 } 145 146 // “用str替换StringBuilder中从start(包括)到end(不包括)的内容” 147 public StringBuilder replace(int start, int end, String str) { 148 super.replace(start, end, str); 149 return this; 150 } 151 152 // “在StringBuilder的位置index处插入‘str中从offset开始的内容’,插入内容长度是len” 153 public StringBuilder insert(int index, char[] str, int offset, 154 int len) 155 { 156 super.insert(index, str, offset, len); 157 return this; 158 } 159 160 // “在StringBuilder的位置offset处插入obj对应的字符串” 161 public StringBuilder insert(int offset, Object obj) { 162 return insert(offset, String.valueOf(obj)); 163 } 164 165 // “在StringBuilder的位置offset处插入str” 166 public StringBuilder insert(int offset, String str) { 167 super.insert(offset, str); 168 return this; 169 } 170 171 // “在StringBuilder的位置offset处插入str” 172 public StringBuilder insert(int offset, char[] str) { 173 super.insert(offset, str); 174 return this; 175 } 176 177 // “在StringBuilder的位置dstOffset处插入s” 178 public StringBuilder insert(int dstOffset, CharSequence s) { 179 if (s == null) 180 s = "null"; 181 if (s instanceof String) 182 return this.insert(dstOffset, (String)s); 183 return this.insert(dstOffset, s, 0, s.length()); 184 } 185 186 // “在StringBuilder的位置dstOffset处插入's中从start到end的内容'” 187 public StringBuilder insert(int dstOffset, CharSequence s, 188 int start, int end) 189 { 190 super.insert(dstOffset, s, start, end); 191 return this; 192 } 193 194 // “在StringBuilder的位置Offset处插入b” 195 public StringBuilder insert(int offset, boolean b) { 196 super.insert(offset, b); 197 return this; 198 } 199 200 // “在StringBuilder的位置Offset处插入c” 201 public StringBuilder insert(int offset, char c) { 202 super.insert(offset, c); 203 return this; 204 } 205 206 // “在StringBuilder的位置Offset处插入i” 207 public StringBuilder insert(int offset, int i) { 208 return insert(offset, String.valueOf(i)); 209 } 210 211 // “在StringBuilder的位置Offset处插入l” 212 public StringBuilder insert(int offset, long l) { 213 return insert(offset, String.valueOf(l)); 214 } 215 216 // “在StringBuilder的位置Offset处插入f” 217 public StringBuilder insert(int offset, float f) { 218 return insert(offset, String.valueOf(f)); 219 } 220 221 // “在StringBuilder的位置Offset处插入d” 222 public StringBuilder insert(int offset, double d) { 223 return insert(offset, String.valueOf(d)); 224 } 225 226 // 返回“str”在StringBuilder的位置 227 public int indexOf(String str) { 228 return indexOf(str, 0); 229 } 230 231 // 从fromIndex开始查找,返回“str”在StringBuilder的位置 232 public int indexOf(String str, int fromIndex) { 233 return String.indexOf(value, 0, count, 234 str.toCharArray(), 0, str.length(), fromIndex); 235 } 236 237 // 从后向前查找,返回“str”在StringBuilder的位置 238 public int lastIndexOf(String str) { 239 return lastIndexOf(str, count); 240 } 241 242 // 从fromIndex开始,从后向前查找,返回“str”在StringBuilder的位置 243 public int lastIndexOf(String str, int fromIndex) { 244 return String.lastIndexOf(value, 0, count, 245 str.toCharArray(), 0, str.length(), fromIndex); 246 } 247 248 // 反转StringBuilder 249 public StringBuilder reverse() { 250 super.reverse(); 251 return this; 252 } 253 254 public String toString() { 255 // Create a copy, don't share the array 256 return new String(value, 0, count); 257 } 258 259 // 序列化对应的写入函数 260 private void writeObject(java.io.ObjectOutputStream s) 261 throws java.io.IOException { 262 s.defaultWriteObject(); 263 s.writeInt(count); 264 s.writeObject(value); 265 } 266 267 // 序列化对应的读取函数 268 private void readObject(java.io.ObjectInputStream s) 269 throws java.io.IOException, ClassNotFoundException { 270 s.defaultReadObject(); 271 count = s.readInt(); 272 value = (char[]) s.readObject(); 273 } 274 }
1. StringBuilder 中插入(insert)相关的API
源码如下(StringBuilderInsertTest.java):
1 /** 2 * StringBuilder 的insert()示例 3 * 4 * @author skywang 5 */ 6 import java.util.HashMap; 7 8 public class StringBuilderInsertTest { 9 10 public static void main(String[] args) { 11 testInsertAPIs() ; 12 } 13 14 /** 15 * StringBuilder 的insert()示例 16 */ 17 private static void testInsertAPIs() { 18 19 System.out.println("-------------------------------- testInsertAPIs -------------------------------"); 20 21 StringBuilder sbuilder = new StringBuilder(); 22 23 // 在位置0处插入字符数组 24 sbuilder.insert(0, new char[]{'a','b','c','d','e'}); 25 // 在位置0处插入字符数组。0表示字符数组起始位置,3表示长度 26 sbuilder.insert(0, new char[]{'A','B','C','D','E'}, 0, 3); 27 // 在位置0处插入float 28 sbuilder.insert(0, 1.414f); 29 // 在位置0处插入double 30 sbuilder.insert(0, 3.14159d); 31 // 在位置0处插入boolean 32 sbuilder.insert(0, true); 33 // 在位置0处插入char 34 sbuilder.insert(0, '\n'); 35 // 在位置0处插入int 36 sbuilder.insert(0, 100); 37 // 在位置0处插入long 38 sbuilder.insert(0, 12345L); 39 // 在位置0处插入StringBuilder对象 40 sbuilder.insert(0, new StringBuilder("StringBuilder")); 41 // 在位置0处插入StringBuilder对象。6表示被在位置0处插入对象的起始位置(包括),13是结束位置(不包括) 42 sbuilder.insert(0, new StringBuilder("STRINGBUILDER"), 6, 13); 43 // 在位置0处插入StringBuffer对象。 44 sbuilder.insert(0, new StringBuffer("StringBuffer")); 45 // 在位置0处插入StringBuffer对象。6表示被在位置0处插入对象的起始位置(包括),12是结束位置(不包括) 46 sbuilder.insert(0, new StringBuffer("STRINGBUFFER"), 6, 12); 47 // 在位置0处插入String对象。 48 sbuilder.insert(0, "String"); 49 // 在位置0处插入String对象。1表示被在位置0处插入对象的起始位置(包括),6是结束位置(不包括) 50 sbuilder.insert(0, "0123456789", 1, 6); 51 sbuilder.insert(0, '\n'); 52 53 // 在位置0处插入Object对象。此处以HashMap为例 54 HashMap map = new HashMap(); 55 map.put("1", "one"); 56 map.put("2", "two"); 57 map.put("3", "three"); 58 sbuilder.insert(0, map); 59 60 System.out.printf("%s\n\n", sbuilder); 61 } 62 }
运行结果:
-------------------------------- testInsertAPIs -------------------------------
{3=three, 2=two, 1=one}
12345StringBUFFERStringBufferBUILDERStringBuilder12345100
true3.141591.414ABCabcde
2. StringBuilder 中追加(append)相关的API
源码如下(StringBuilderAppendTest.java):
1 /** 2 * StringBuilder 的append()示例 3 * 4 * @author skywang 5 */ 6 import java.util.HashMap; 7 8 public class StringBuilderAppendTest { 9 10 public static void main(String[] args) { 11 testAppendAPIs() ; 12 } 13 14 /** 15 * StringBuilder 的append()示例 16 */ 17 private static void testAppendAPIs() { 18 19 System.out.println("-------------------------------- testAppendAPIs -------------------------------"); 20 21 StringBuilder sbuilder = new StringBuilder(); 22 23 // 追加字符数组 24 sbuilder.append(new char[]{'a','b','c','d','e'}); 25 // 追加字符数组。0表示字符数组起始位置,3表示长度 26 sbuilder.append(new char[]{'A','B','C','D','E'}, 0, 3); 27 // 追加float 28 sbuilder.append(1.414f); 29 // 追加double 30 sbuilder.append(3.14159d); 31 // 追加boolean 32 sbuilder.append(true); 33 // 追加char 34 sbuilder.append('\n'); 35 // 追加int 36 sbuilder.append(100); 37 // 追加long 38 sbuilder.append(12345L); 39 // 追加StringBuilder对象 40 sbuilder.append(new StringBuilder("StringBuilder")); 41 // 追加StringBuilder对象。6表示被追加对象的起始位置(包括),13是结束位置(不包括) 42 sbuilder.append(new StringBuilder("STRINGBUILDER"), 6, 13); 43 // 追加StringBuffer对象。 44 sbuilder.append(new StringBuffer("StringBuffer")); 45 // 追加StringBuffer对象。6表示被追加对象的起始位置(包括),12是结束位置(不包括) 46 sbuilder.append(new StringBuffer("STRINGBUFFER"), 6, 12); 47 // 追加String对象。 48 sbuilder.append("String"); 49 // 追加String对象。1表示被追加对象的起始位置(包括),6是结束位置(不包括) 50 sbuilder.append("0123456789", 1, 6); 51 sbuilder.append('\n'); 52 53 // 追加Object对象。此处以HashMap为例 54 HashMap map = new HashMap(); 55 map.put("1", "one"); 56 map.put("2", "two"); 57 map.put("3", "three"); 58 sbuilder.append(map); 59 sbuilder.append('\n'); 60 61 // 追加unicode编码 62 sbuilder.appendCodePoint(0x5b57); // 0x5b57是“字”的unicode编码 63 sbuilder.appendCodePoint(0x7b26); // 0x7b26是“符”的unicode编码 64 sbuilder.appendCodePoint(0x7f16); // 0x7f16是“编”的unicode编码 65 sbuilder.appendCodePoint(0x7801); // 0x7801是“码”的unicode编码 66 67 System.out.printf("%s\n\n", sbuilder); 68 } 69 }
运行结果:
-------------------------------- testAppendAPIs -------------------------------
abcdeABC1.4143.14159true
10012345StringBuilderBUILDERStringBufferBUFFERString12345
{3=three, 2=two, 1=one}
字符编码
3. StringBuilder 中替换(replace)相关的API
源码如下(StringBuilderReplaceTest.java):
1 /** 2 * StringBuilder 的replace()示例 3 * 4 * @author skywang 5 */ 6 import java.util.HashMap; 7 8 public class StringBuilderReplaceTest { 9 10 public static void main(String[] args) { 11 testReplaceAPIs() ; 12 } 13 14 /** 15 * StringBuilder 的replace()示例 16 */ 17 private static void testReplaceAPIs() { 18 19 System.out.println("-------------------------------- testReplaceAPIs ------------------------------"); 20 21 StringBuilder sbuilder; 22 23 sbuilder = new StringBuilder("0123456789"); 24 sbuilder.replace(0, 3, "ABCDE"); 25 System.out.printf("sbuilder=%s\n", sbuilder); 26 27 sbuilder = new StringBuilder("0123456789"); 28 sbuilder.reverse(); 29 System.out.printf("sbuilder=%s\n", sbuilder); 30 31 sbuilder = new StringBuilder("0123456789"); 32 sbuilder.setCharAt(0, 'M'); 33 System.out.printf("sbuilder=%s\n", sbuilder); 34 35 System.out.println(); 36 } 37 }
运行结果:
-------------------------------- testReplaceAPIs ------------------------------
sbuilder=ABCDE3456789
sbuilder=9876543210
sbuilder=M123456789
4. StringBuilder 中删除(delete)相关的API
源码如下(StringBuilderDeleteTest.java):
1 /** 2 * StringBuilder 的delete()示例 3 * 4 * @author skywang 5 */ 6 import java.util.HashMap; 7 8 public class StringBuilderDeleteTest { 9 10 public static void main(String[] args) { 11 testDeleteAPIs() ; 12 } 13 14 /** 15 * StringBuilder 的delete()示例 16 */ 17 private static void testDeleteAPIs() { 18 19 System.out.println("-------------------------------- testDeleteAPIs -------------------------------"); 20 21 StringBuilder sbuilder = new StringBuilder("0123456789"); 22 23 // 删除位置0的字符,剩余字符是“123456789”。 24 sbuilder.deleteCharAt(0); 25 // 删除位置3(包括)到位置6(不包括)之间的字符,剩余字符是“123789”。 26 sbuilder.delete(3,6); 27 28 // 获取sb中从位置1开始的字符串 29 String str1 = sbuilder.substring(1); 30 // 获取sb中从位置3(包括)到位置5(不包括)之间的字符串 31 String str2 = sbuilder.substring(3, 5); 32 // 获取sb中从位置3(包括)到位置5(不包括)之间的字符串,获取的对象是CharSequence对象,此处转型为String 33 String str3 = (String)sbuilder.subSequence(3, 5); 34 35 System.out.printf("sbuilder=%s\nstr1=%s\nstr2=%s\nstr3=%s\n", 36 sbuilder, str1, str2, str3); 37 } 38 }
运行结果:
-------------------------------- testDeleteAPIs -------------------------------
sbuilder=123789
str1=23789
str2=78
str3=78
5. StringBuilder 中index相关的API
源码如下(StringBuilderIndexTest.java):
1 /** 2 * StringBuilder 中index相关API演示 3 * 4 * @author skywang 5 */ 6 import java.util.HashMap; 7 8 public class StringBuilderIndexTest { 9 10 public static void main(String[] args) { 11 testIndexAPIs() ; 12 } 13 14 /** 15 * StringBuilder 中index相关API演示 16 */ 17 private static void testIndexAPIs() { 18 System.out.println("-------------------------------- testIndexAPIs --------------------------------"); 19 20 StringBuilder sbuilder = new StringBuilder("abcAbcABCabCaBcAbCaBCabc"); 21 System.out.printf("sbuilder=%s\n", sbuilder); 22 23 // 1. 从前往后,找出"bc"第一次出现的位置 24 System.out.printf("%-30s = %d\n", "sbuilder.indexOf(\"bc\")", sbuilder.indexOf("bc")); 25 26 // 2. 从位置5开始,从前往后,找出"bc"第一次出现的位置 27 System.out.printf("%-30s = %d\n", "sbuilder.indexOf(\"bc\", 5)", sbuilder.indexOf("bc", 5)); 28 29 // 3. 从后往前,找出"bc"第一次出现的位置 30 System.out.printf("%-30s = %d\n", "sbuilder.lastIndexOf(\"bc\")", sbuilder.lastIndexOf("bc")); 31 32 // 4. 从位置4开始,从后往前,找出"bc"第一次出现的位置 33 System.out.printf("%-30s = %d\n", "sbuilder.lastIndexOf(\"bc\", 4)", sbuilder.lastIndexOf("bc", 4)); 34 35 System.out.println(); 36 } 37 }
运行结果:
-------------------------------- 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):
1 /** 2 * StringBuilder 的其它API示例 3 * 4 * @author skywang 5 */ 6 import java.util.HashMap; 7 8 public class StringBuilderOtherTest { 9 10 public static void main(String[] args) { 11 testOtherAPIs() ; 12 } 13 14 /** 15 * StringBuilder 的其它API示例 16 */ 17 private static void testOtherAPIs() { 18 19 System.out.println("-------------------------------- testOtherAPIs --------------------------------"); 20 21 StringBuilder sbuilder = new StringBuilder("0123456789"); 22 23 int cap = sbuilder.capacity(); 24 System.out.printf("cap=%d\n", cap); 25 26 char c = sbuilder.charAt(6); 27 System.out.printf("c=%c\n", c); 28 29 char[] carr = new char[4]; 30 sbuilder.getChars(3, 7, carr, 0); 31 for (int i=0; i<carr.length; i++) 32 System.out.printf("carr[%d]=%c ", i, carr[i]); 33 System.out.println(); 34 35 System.out.println(); 36 } 37 }
运行结果:
-------------------------------- testOtherAPIs --------------------------------
cap=26
c=6
carr[0]=3 carr[1]=4 carr[2]=5 carr[3]=6
7. StringBuilder 完整示例
下面的示例是整合上面的几个示例的完整的StringBuilder演示程序,源码如下(StringBuilderTest.java):
1 /** 2 * StringBuilder 演示程序 3 * 4 * @author skywang 5 */ 6 import java.util.HashMap; 7 8 public class StringBuilderTest { 9 10 public static void main(String[] args) { 11 testOtherAPIs() ; 12 testIndexAPIs() ; 13 testInsertAPIs() ; 14 testAppendAPIs() ; 15 testReplaceAPIs() ; 16 testDeleteAPIs() ; 17 } 18 19 /** 20 * StringBuilder 的其它API示例 21 */ 22 private static void testOtherAPIs() { 23 24 System.out.println("-------------------------------- testOtherAPIs --------------------------------"); 25 26 StringBuilder sbuilder = new StringBuilder("0123456789"); 27 28 int cap = sbuilder.capacity(); 29 System.out.printf("cap=%d\n", cap); 30 31 char c = sbuilder.charAt(6); 32 System.out.printf("c=%c\n", c); 33 34 char[] carr = new char[4]; 35 sbuilder.getChars(3, 7, carr, 0); 36 for (int i=0; i<carr.length; i++) 37 System.out.printf("carr[%d]=%c ", i, carr[i]); 38 System.out.println(); 39 40 System.out.println(); 41 } 42 43 /** 44 * StringBuilder 中index相关API演示 45 */ 46 private static void testIndexAPIs() { 47 System.out.println("-------------------------------- testIndexAPIs --------------------------------"); 48 49 StringBuilder sbuilder = new StringBuilder("abcAbcABCabCaBcAbCaBCabc"); 50 System.out.printf("sbuilder=%s\n", sbuilder); 51 52 // 1. 从前往后,找出"bc"第一次出现的位置 53 System.out.printf("%-30s = %d\n", "sbuilder.indexOf(\"bc\")", sbuilder.indexOf("bc")); 54 55 // 2. 从位置5开始,从前往后,找出"bc"第一次出现的位置 56 System.out.printf("%-30s = %d\n", "sbuilder.indexOf(\"bc\", 5)", sbuilder.indexOf("bc", 5)); 57 58 // 3. 从后往前,找出"bc"第一次出现的位置 59 System.out.printf("%-30s = %d\n", "sbuilder.lastIndexOf(\"bc\")", sbuilder.lastIndexOf("bc")); 60 61 // 4. 从位置4开始,从后往前,找出"bc"第一次出现的位置 62 System.out.printf("%-30s = %d\n", "sbuilder.lastIndexOf(\"bc\", 4)", sbuilder.lastIndexOf("bc", 4)); 63 64 System.out.println(); 65 } 66 67 /** 68 * StringBuilder 的replace()示例 69 */ 70 private static void testReplaceAPIs() { 71 72 System.out.println("-------------------------------- testReplaceAPIs ------------------------------"); 73 74 StringBuilder sbuilder; 75 76 sbuilder = new StringBuilder("0123456789"); 77 sbuilder.replace(0, 3, "ABCDE"); 78 System.out.printf("sbuilder=%s\n", sbuilder); 79 80 sbuilder = new StringBuilder("0123456789"); 81 sbuilder.reverse(); 82 System.out.printf("sbuilder=%s\n", sbuilder); 83 84 sbuilder = new StringBuilder("0123456789"); 85 sbuilder.setCharAt(0, 'M'); 86 System.out.printf("sbuilder=%s\n", sbuilder); 87 88 System.out.println(); 89 } 90 91 /** 92 * StringBuilder 的delete()示例 93 */ 94 private static void testDeleteAPIs() { 95 96 System.out.println("-------------------------------- testDeleteAPIs -------------------------------"); 97 98 StringBuilder sbuilder = new StringBuilder("0123456789"); 99 100 // 删除位置0的字符,剩余字符是“123456789”。 101 sbuilder.deleteCharAt(0); 102 // 删除位置3(包括)到位置6(不包括)之间的字符,剩余字符是“123789”。 103 sbuilder.delete(3,6); 104 105 // 获取sb中从位置1开始的字符串 106 String str1 = sbuilder.substring(1); 107 // 获取sb中从位置3(包括)到位置5(不包括)之间的字符串 108 String str2 = sbuilder.substring(3, 5); 109 // 获取sb中从位置3(包括)到位置5(不包括)之间的字符串,获取的对象是CharSequence对象,此处转型为String 110 String str3 = (String)sbuilder.subSequence(3, 5); 111 112 System.out.printf("sbuilder=%s\nstr1=%s\nstr2=%s\nstr3=%s\n", 113 sbuilder, str1, str2, str3); 114 } 115 116 /** 117 * StringBuilder 的insert()示例 118 */ 119 private static void testInsertAPIs() { 120 121 System.out.println("-------------------------------- testInsertAPIs -------------------------------"); 122 123 StringBuilder sbuilder = new StringBuilder(); 124 125 // 在位置0处插入字符数组 126 sbuilder.insert(0, new char[]{'a','b','c','d','e'}); 127 // 在位置0处插入字符数组。0表示字符数组起始位置,3表示长度 128 sbuilder.insert(0, new char[]{'A','B','C','D','E'}, 0, 3); 129 // 在位置0处插入float 130 sbuilder.insert(0, 1.414f); 131 // 在位置0处插入double 132 sbuilder.insert(0, 3.14159d); 133 // 在位置0处插入boolean 134 sbuilder.insert(0, true); 135 // 在位置0处插入char 136 sbuilder.insert(0, '\n'); 137 // 在位置0处插入int 138 sbuilder.insert(0, 100); 139 // 在位置0处插入long 140 sbuilder.insert(0, 12345L); 141 // 在位置0处插入StringBuilder对象 142 sbuilder.insert(0, new StringBuilder("StringBuilder")); 143 // 在位置0处插入StringBuilder对象。6表示被在位置0处插入对象的起始位置(包括),13是结束位置(不包括) 144 sbuilder.insert(0, new StringBuilder("STRINGBUILDER"), 6, 13); 145 // 在位置0处插入StringBuffer对象。 146 sbuilder.insert(0, new StringBuffer("StringBuffer")); 147 // 在位置0处插入StringBuffer对象。6表示被在位置0处插入对象的起始位置(包括),12是结束位置(不包括) 148 sbuilder.insert(0, new StringBuffer("STRINGBUFFER"), 6, 12); 149 // 在位置0处插入String对象。 150 sbuilder.insert(0, "String"); 151 // 在位置0处插入String对象。1表示被在位置0处插入对象的起始位置(包括),6是结束位置(不包括) 152 sbuilder.insert(0, "0123456789", 1, 6); 153 sbuilder.insert(0, '\n'); 154 155 // 在位置0处插入Object对象。此处以HashMap为例 156 HashMap map = new HashMap(); 157 map.put("1", "one"); 158 map.put("2", "two"); 159 map.put("3", "three"); 160 sbuilder.insert(0, map); 161 162 System.out.printf("%s\n\n", sbuilder); 163 } 164 165 /** 166 * StringBuilder 的append()示例 167 */ 168 private static void testAppendAPIs() { 169 170 System.out.println("-------------------------------- testAppendAPIs -------------------------------"); 171 172 StringBuilder sbuilder = new StringBuilder(); 173 174 // 追加字符数组 175 sbuilder.append(new char[]{'a','b','c','d','e'}); 176 // 追加字符数组。0表示字符数组起始位置,3表示长度 177 sbuilder.append(new char[]{'A','B','C','D','E'}, 0, 3); 178 // 追加float 179 sbuilder.append(1.414f); 180 // 追加double 181 sbuilder.append(3.14159d); 182 // 追加boolean 183 sbuilder.append(true); 184 // 追加char 185 sbuilder.append('\n'); 186 // 追加int 187 sbuilder.append(100); 188 // 追加long 189 sbuilder.append(12345L); 190 // 追加StringBuilder对象 191 sbuilder.append(new StringBuilder("StringBuilder")); 192 // 追加StringBuilder对象。6表示被追加对象的起始位置(包括),13是结束位置(不包括) 193 sbuilder.append(new StringBuilder("STRINGBUILDER"), 6, 13); 194 // 追加StringBuffer对象。 195 sbuilder.append(new StringBuffer("StringBuffer")); 196 // 追加StringBuffer对象。6表示被追加对象的起始位置(包括),12是结束位置(不包括) 197 sbuilder.append(new StringBuffer("STRINGBUFFER"), 6, 12); 198 // 追加String对象。 199 sbuilder.append("String"); 200 // 追加String对象。1表示被追加对象的起始位置(包括),6是结束位置(不包括) 201 sbuilder.append("0123456789", 1, 6); 202 sbuilder.append('\n'); 203 204 // 追加Object对象。此处以HashMap为例 205 HashMap map = new HashMap(); 206 map.put("1", "one"); 207 map.put("2", "two"); 208 map.put("3", "three"); 209 sbuilder.append(map); 210 sbuilder.append('\n'); 211 212 // 追加unicode编码 213 sbuilder.appendCodePoint(0x5b57); // 0x5b57是“字”的unicode编码 214 sbuilder.appendCodePoint(0x7b26); // 0x7b26是“符”的unicode编码 215 sbuilder.appendCodePoint(0x7f16); // 0x7f16是“编”的unicode编码 216 sbuilder.appendCodePoint(0x7801); // 0x7801是“码”的unicode编码 217 218 System.out.printf("%s\n\n", sbuilder); 219 } 220 }