本章介绍StringBuilder以及它的API的详细使用方法。

转载请注明出处:http://www.cnblogs.com/skywang12345/p/string02.html

StringBuilder 是一个可变的字符序列。它继承于AbstractStringBuilder,实现了CharSequence接口。
StringBuffer 也是继承于AbstractStringBuilder的子类;但是,StringBuilder和StringBuffer不同,前者是非线程安全的,后者是线程安全的。

StringBuilder 和 CharSequence之间的关系图如下:

StringBuilder函数列表

  1. StringBuilder()
  2. StringBuilder(int capacity)
  3. StringBuilder(CharSequence seq)
  4. StringBuilder(String str)
  5. StringBuilder append(float f)
  6. StringBuilder append(double d)
  7. StringBuilder append(boolean b)
  8. StringBuilder append(int i)
  9. StringBuilder append(long l)
  10. StringBuilder append(char c)
  11. StringBuilder append(char[] chars)
  12. StringBuilder append(char[] str, int offset, int len)
  13. StringBuilder append(String str)
  14. StringBuilder append(Object obj)
  15. StringBuilder append(StringBuffer sb)
  16. StringBuilder append(CharSequence csq)
  17. StringBuilder append(CharSequence csq, int start, int end)
  18. StringBuilder appendCodePoint(int codePoint)
  19. int capacity()
  20. char charAt(int index)
  21. int codePointAt(int index)
  22. int codePointBefore(int index)
  23. int codePointCount(int start, int end)
  24. StringBuilder delete(int start, int end)
  25. StringBuilder deleteCharAt(int index)
  26. void ensureCapacity(int min)
  27. void getChars(int start, int end, char[] dst, int dstStart)
  28. int indexOf(String subString, int start)
  29. int indexOf(String string)
  30. StringBuilder insert(int offset, boolean b)
  31. StringBuilder insert(int offset, int i)
  32. StringBuilder insert(int offset, long l)
  33. StringBuilder insert(int offset, float f)
  34. StringBuilder insert(int offset, double d)
  35. StringBuilder insert(int offset, char c)
  36. StringBuilder insert(int offset, char[] ch)
  37. StringBuilder insert(int offset, char[] str, int strOffset, int strLen)
  38. StringBuilder insert(int offset, String str)
  39. StringBuilder insert(int offset, Object obj)
  40. StringBuilder insert(int offset, CharSequence s)
  41. StringBuilder insert(int offset, CharSequence s, int start, int end)
  42. int lastIndexOf(String string)
  43. int lastIndexOf(String subString, int start)
  44. int length()
  45. int offsetByCodePoints(int index, int codePointOffset)
  46. StringBuilder replace(int start, int end, String string)
  47. StringBuilder reverse()
  48. void setCharAt(int index, char ch)
  49. void setLength(int length)
  50. CharSequence subSequence(int start, int end)
  51. String substring(int start)
  52. String substring(int start, int end)
  53. String toString()
  54. void trimToSize()

 

AbstractStringBuilder源码(基于jdk1.7.40)

  1. 1 package java.lang;
  2. 2
  3. 3 import sun.misc.FloatingDecimal;
  4. 4 import java.util.Arrays;
  5. 5
  6. 6 abstract class AbstractStringBuilder implements Appendable, CharSequence {
  7. 7 char[] value;
  8. 8
  9. 9 int count;
  10. 10
  11. 11 AbstractStringBuilder() {
  12. 12 }
  13. 13
  14. 14 AbstractStringBuilder(int capacity) {
  15. 15 value = new char[capacity];
  16. 16 }
  17. 17
  18. 18 public int length() {
  19. 19 return count;
  20. 20 }
  21. 21
  22. 22 public int capacity() {
  23. 23 return value.length;
  24. 24 }
  25. 25
  26. 26 public void ensureCapacity(int minimumCapacity) {
  27. 27 if (minimumCapacity > 0)
  28. 28 ensureCapacityInternal(minimumCapacity);
  29. 29 }
  30. 30
  31. 31 private void ensureCapacityInternal(int minimumCapacity) {
  32. 32 // overflow-conscious code
  33. 33 if (minimumCapacity - value.length > 0)
  34. 34 expandCapacity(minimumCapacity);
  35. 35 }
  36. 36
  37. 37 void expandCapacity(int minimumCapacity) {
  38. 38 int newCapacity = value.length * 2 + 2;
  39. 39 if (newCapacity - minimumCapacity < 0)
  40. 40 newCapacity = minimumCapacity;
  41. 41 if (newCapacity < 0) {
  42. 42 if (minimumCapacity < 0) // overflow
  43. 43 throw new OutOfMemoryError();
  44. 44 newCapacity = Integer.MAX_VALUE;
  45. 45 }
  46. 46 value = Arrays.copyOf(value, newCapacity);
  47. 47 }
  48. 48
  49. 49 public void trimToSize() {
  50. 50 if (count < value.length) {
  51. 51 value = Arrays.copyOf(value, count);
  52. 52 }
  53. 53 }
  54. 54
  55. 55 public void setLength(int newLength) {
  56. 56 if (newLength < 0)
  57. 57 throw new StringIndexOutOfBoundsException(newLength);
  58. 58 ensureCapacityInternal(newLength);
  59. 59
  60. 60 if (count < newLength) {
  61. 61 for (; count < newLength; count++)
  62. 62 value[count] = \'\0\';
  63. 63 } else {
  64. 64 count = newLength;
  65. 65 }
  66. 66 }
  67. 67
  68. 68 public char charAt(int index) {
  69. 69 if ((index < 0) || (index >= count))
  70. 70 throw new StringIndexOutOfBoundsException(index);
  71. 71 return value[index];
  72. 72 }
  73. 73
  74. 74 public int codePointAt(int index) {
  75. 75 if ((index < 0) || (index >= count)) {
  76. 76 throw new StringIndexOutOfBoundsException(index);
  77. 77 }
  78. 78 return Character.codePointAt(value, index);
  79. 79 }
  80. 80
  81. 81 public int codePointBefore(int index) {
  82. 82 int i = index - 1;
  83. 83 if ((i < 0) || (i >= count)) {
  84. 84 throw new StringIndexOutOfBoundsException(index);
  85. 85 }
  86. 86 return Character.codePointBefore(value, index);
  87. 87 }
  88. 88
  89. 89 public int codePointCount(int beginIndex, int endIndex) {
  90. 90 if (beginIndex < 0 || endIndex > count || beginIndex > endIndex) {
  91. 91 throw new IndexOutOfBoundsException();
  92. 92 }
  93. 93 return Character.codePointCountImpl(value, beginIndex, endIndex-beginIndex);
  94. 94 }
  95. 95
  96. 96 public int offsetByCodePoints(int index, int codePointOffset) {
  97. 97 if (index < 0 || index > count) {
  98. 98 throw new IndexOutOfBoundsException();
  99. 99 }
  100. 100 return Character.offsetByCodePointsImpl(value, 0, count,
  101. 101 index, codePointOffset);
  102. 102 }
  103. 103
  104. 104 public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
  105. 105 {
  106. 106 if (srcBegin < 0)
  107. 107 throw new StringIndexOutOfBoundsException(srcBegin);
  108. 108 if ((srcEnd < 0) || (srcEnd > count))
  109. 109 throw new StringIndexOutOfBoundsException(srcEnd);
  110. 110 if (srcBegin > srcEnd)
  111. 111 throw new StringIndexOutOfBoundsException("srcBegin > srcEnd");
  112. 112 System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
  113. 113 }
  114. 114
  115. 115 public void setCharAt(int index, char ch) {
  116. 116 if ((index < 0) || (index >= count))
  117. 117 throw new StringIndexOutOfBoundsException(index);
  118. 118 value[index] = ch;
  119. 119 }
  120. 120
  121. 121 public AbstractStringBuilder append(Object obj) {
  122. 122 return append(String.valueOf(obj));
  123. 123 }
  124. 124
  125. 125 public AbstractStringBuilder append(String str) {
  126. 126 if (str == null) str = "null";
  127. 127 int len = str.length();
  128. 128 ensureCapacityInternal(count + len);
  129. 129 str.getChars(0, len, value, count);
  130. 130 count += len;
  131. 131 return this;
  132. 132 }
  133. 133
  134. 134 // Documentation in subclasses because of synchro difference
  135. 135 public AbstractStringBuilder append(StringBuffer sb) {
  136. 136 if (sb == null)
  137. 137 return append("null");
  138. 138 int len = sb.length();
  139. 139 ensureCapacityInternal(count + len);
  140. 140 sb.getChars(0, len, value, count);
  141. 141 count += len;
  142. 142 return this;
  143. 143 }
  144. 144
  145. 145 // Documentation in subclasses because of synchro difference
  146. 146 public AbstractStringBuilder append(CharSequence s) {
  147. 147 if (s == null)
  148. 148 s = "null";
  149. 149 if (s instanceof String)
  150. 150 return this.append((String)s);
  151. 151 if (s instanceof StringBuffer)
  152. 152 return this.append((StringBuffer)s);
  153. 153 return this.append(s, 0, s.length());
  154. 154 }
  155. 155
  156. 156 public AbstractStringBuilder append(CharSequence s, int start, int end) {
  157. 157 if (s == null)
  158. 158 s = "null";
  159. 159 if ((start < 0) || (start > end) || (end > s.length()))
  160. 160 throw new IndexOutOfBoundsException(
  161. 161 "start " + start + ", end " + end + ", s.length() "
  162. 162 + s.length());
  163. 163 int len = end - start;
  164. 164 ensureCapacityInternal(count + len);
  165. 165 for (int i = start, j = count; i < end; i++, j++)
  166. 166 value[j] = s.charAt(i);
  167. 167 count += len;
  168. 168 return this;
  169. 169 }
  170. 170
  171. 171 public AbstractStringBuilder append(char[] str) {
  172. 172 int len = str.length;
  173. 173 ensureCapacityInternal(count + len);
  174. 174 System.arraycopy(str, 0, value, count, len);
  175. 175 count += len;
  176. 176 return this;
  177. 177 }
  178. 178
  179. 179 public AbstractStringBuilder append(char str[], int offset, int len) {
  180. 180 if (len > 0) // let arraycopy report AIOOBE for len < 0
  181. 181 ensureCapacityInternal(count + len);
  182. 182 System.arraycopy(str, offset, value, count, len);
  183. 183 count += len;
  184. 184 return this;
  185. 185 }
  186. 186
  187. 187 public AbstractStringBuilder append(boolean b) {
  188. 188 if (b) {
  189. 189 ensureCapacityInternal(count + 4);
  190. 190 value[count++] = \'t\';
  191. 191 value[count++] = \'r\';
  192. 192 value[count++] = \'u\';
  193. 193 value[count++] = \'e\';
  194. 194 } else {
  195. 195 ensureCapacityInternal(count + 5);
  196. 196 value[count++] = \'f\';
  197. 197 value[count++] = \'a\';
  198. 198 value[count++] = \'l\';
  199. 199 value[count++] = \'s\';
  200. 200 value[count++] = \'e\';
  201. 201 }
  202. 202 return this;
  203. 203 }
  204. 204
  205. 205 public AbstractStringBuilder append(char c) {
  206. 206 ensureCapacityInternal(count + 1);
  207. 207 value[count++] = c;
  208. 208 return this;
  209. 209 }
  210. 210
  211. 211 public AbstractStringBuilder append(int i) {
  212. 212 if (i == Integer.MIN_VALUE) {
  213. 213 append("-2147483648");
  214. 214 return this;
  215. 215 }
  216. 216 int appendedLength = (i < 0) ? Integer.stringSize(-i) + 1
  217. 217 : Integer.stringSize(i);
  218. 218 int spaceNeeded = count + appendedLength;
  219. 219 ensureCapacityInternal(spaceNeeded);
  220. 220 Integer.getChars(i, spaceNeeded, value);
  221. 221 count = spaceNeeded;
  222. 222 return this;
  223. 223 }
  224. 224
  225. 225 public AbstractStringBuilder append(long l) {
  226. 226 if (l == Long.MIN_VALUE) {
  227. 227 append("-9223372036854775808");
  228. 228 return this;
  229. 229 }
  230. 230 int appendedLength = (l < 0) ? Long.stringSize(-l) + 1
  231. 231 : Long.stringSize(l);
  232. 232 int spaceNeeded = count + appendedLength;
  233. 233 ensureCapacityInternal(spaceNeeded);
  234. 234 Long.getChars(l, spaceNeeded, value);
  235. 235 count = spaceNeeded;
  236. 236 return this;
  237. 237 }
  238. 238
  239. 239 public AbstractStringBuilder append(float f) {
  240. 240 new FloatingDecimal(f).appendTo(this);
  241. 241 return this;
  242. 242 }
  243. 243
  244. 244 public AbstractStringBuilder append(double d) {
  245. 245 new FloatingDecimal(d).appendTo(this);
  246. 246 return this;
  247. 247 }
  248. 248
  249. 249 public AbstractStringBuilder delete(int start, int end) {
  250. 250 if (start < 0)
  251. 251 throw new StringIndexOutOfBoundsException(start);
  252. 252 if (end > count)
  253. 253 end = count;
  254. 254 if (start > end)
  255. 255 throw new StringIndexOutOfBoundsException();
  256. 256 int len = end - start;
  257. 257 if (len > 0) {
  258. 258 System.arraycopy(value, start+len, value, start, count-end);
  259. 259 count -= len;
  260. 260 }
  261. 261 return this;
  262. 262 }
  263. 263
  264. 264 public AbstractStringBuilder appendCodePoint(int codePoint) {
  265. 265 final int count = this.count;
  266. 266
  267. 267 if (Character.isBmpCodePoint(codePoint)) {
  268. 268 ensureCapacityInternal(count + 1);
  269. 269 value[count] = (char) codePoint;
  270. 270 this.count = count + 1;
  271. 271 } else if (Character.isValidCodePoint(codePoint)) {
  272. 272 ensureCapacityInternal(count + 2);
  273. 273 Character.toSurrogates(codePoint, value, count);
  274. 274 this.count = count + 2;
  275. 275 } else {
  276. 276 throw new IllegalArgumentException();
  277. 277 }
  278. 278 return this;
  279. 279 }
  280. 280
  281. 281 public AbstractStringBuilder deleteCharAt(int index) {
  282. 282 if ((index < 0) || (index >= count))
  283. 283 throw new StringIndexOutOfBoundsException(index);
  284. 284 System.arraycopy(value, index+1, value, index, count-index-1);
  285. 285 count--;
  286. 286 return this;
  287. 287 }
  288. 288
  289. 289 public AbstractStringBuilder replace(int start, int end, String str) {
  290. 290 if (start < 0)
  291. 291 throw new StringIndexOutOfBoundsException(start);
  292. 292 if (start > count)
  293. 293 throw new StringIndexOutOfBoundsException("start > length()");
  294. 294 if (start > end)
  295. 295 throw new StringIndexOutOfBoundsException("start > end");
  296. 296
  297. 297 if (end > count)
  298. 298 end = count;
  299. 299 int len = str.length();
  300. 300 int newCount = count + len - (end - start);
  301. 301 ensureCapacityInternal(newCount);
  302. 302
  303. 303 System.arraycopy(value, end, value, start + len, count - end);
  304. 304 str.getChars(value, start);
  305. 305 count = newCount;
  306. 306 return this;
  307. 307 }
  308. 308
  309. 309 public String substring(int start) {
  310. 310 return substring(start, count);
  311. 311 }
  312. 312
  313. 313 public CharSequence subSequence(int start, int end) {
  314. 314 return substring(start, end);
  315. 315 }
  316. 316
  317. 317 public String substring(int start, int end) {
  318. 318 if (start < 0)
  319. 319 throw new StringIndexOutOfBoundsException(start);
  320. 320 if (end > count)
  321. 321 throw new StringIndexOutOfBoundsException(end);
  322. 322 if (start > end)
  323. 323 throw new StringIndexOutOfBoundsException(end - start);
  324. 324 return new String(value, start, end - start);
  325. 325 }
  326. 326
  327. 327 public AbstractStringBuilder insert(int index, char[] str, int offset,
  328. 328 int len)
  329. 329 {
  330. 330 if ((index < 0) || (index > length()))
  331. 331 throw new StringIndexOutOfBoundsException(index);
  332. 332 if ((offset < 0) || (len < 0) || (offset > str.length - len))
  333. 333 throw new StringIndexOutOfBoundsException(
  334. 334 "offset " + offset + ", len " + len + ", str.length "
  335. 335 + str.length);
  336. 336 ensureCapacityInternal(count + len);
  337. 337 System.arraycopy(value, index, value, index + len, count - index);
  338. 338 System.arraycopy(str, offset, value, index, len);
  339. 339 count += len;
  340. 340 return this;
  341. 341 }
  342. 342
  343. 343 public AbstractStringBuilder insert(int offset, Object obj) {
  344. 344 return insert(offset, String.valueOf(obj));
  345. 345 }
  346. 346
  347. 347 public AbstractStringBuilder insert(int offset, String str) {
  348. 348 if ((offset < 0) || (offset > length()))
  349. 349 throw new StringIndexOutOfBoundsException(offset);
  350. 350 if (str == null)
  351. 351 str = "null";
  352. 352 int len = str.length();
  353. 353 ensureCapacityInternal(count + len);
  354. 354 System.arraycopy(value, offset, value, offset + len, count - offset);
  355. 355 str.getChars(value, offset);
  356. 356 count += len;
  357. 357 return this;
  358. 358 }
  359. 359
  360. 360 public AbstractStringBuilder insert(int offset, char[] str) {
  361. 361 if ((offset < 0) || (offset > length()))
  362. 362 throw new StringIndexOutOfBoundsException(offset);
  363. 363 int len = str.length;
  364. 364 ensureCapacityInternal(count + len);
  365. 365 System.arraycopy(value, offset, value, offset + len, count - offset);
  366. 366 System.arraycopy(str, 0, value, offset, len);
  367. 367 count += len;
  368. 368 return this;
  369. 369 }
  370. 370
  371. 371 public AbstractStringBuilder insert(int dstOffset, CharSequence s) {
  372. 372 if (s == null)
  373. 373 s = "null";
  374. 374 if (s instanceof String)
  375. 375 return this.insert(dstOffset, (String)s);
  376. 376 return this.insert(dstOffset, s, 0, s.length());
  377. 377 }
  378. 378
  379. 379 public AbstractStringBuilder insert(int dstOffset, CharSequence s,
  380. 380 int start, int end) {
  381. 381 if (s == null)
  382. 382 s = "null";
  383. 383 if ((dstOffset < 0) || (dstOffset > this.length()))
  384. 384 throw new IndexOutOfBoundsException("dstOffset "+dstOffset);
  385. 385 if ((start < 0) || (end < 0) || (start > end) || (end > s.length()))
  386. 386 throw new IndexOutOfBoundsException(
  387. 387 "start " + start + ", end " + end + ", s.length() "
  388. 388 + s.length());
  389. 389 int len = end - start;
  390. 390 ensureCapacityInternal(count + len);
  391. 391 System.arraycopy(value, dstOffset, value, dstOffset + len,
  392. 392 count - dstOffset);
  393. 393 for (int i=start; i<end; i++)
  394. 394 value[dstOffset++] = s.charAt(i);
  395. 395 count += len;
  396. 396 return this;
  397. 397 }
  398. 398
  399. 399 public AbstractStringBuilder insert(int offset, boolean b) {
  400. 400 return insert(offset, String.valueOf(b));
  401. 401 }
  402. 402
  403. 403 public AbstractStringBuilder insert(int offset, char c) {
  404. 404 ensureCapacityInternal(count + 1);
  405. 405 System.arraycopy(value, offset, value, offset + 1, count - offset);
  406. 406 value[offset] = c;
  407. 407 count += 1;
  408. 408 return this;
  409. 409 }
  410. 410
  411. 411 public AbstractStringBuilder insert(int offset, int i) {
  412. 412 return insert(offset, String.valueOf(i));
  413. 413 }
  414. 414
  415. 415 public AbstractStringBuilder insert(int offset, long l) {
  416. 416 return insert(offset, String.valueOf(l));
  417. 417 }
  418. 418
  419. 419 public AbstractStringBuilder insert(int offset, float f) {
  420. 420 return insert(offset, String.valueOf(f));
  421. 421 }
  422. 422
  423. 423 public AbstractStringBuilder insert(int offset, double d) {
  424. 424 return insert(offset, String.valueOf(d));
  425. 425 }
  426. 426
  427. 427 public int indexOf(String str) {
  428. 428 return indexOf(str, 0);
  429. 429 }
  430. 430
  431. 431 public int indexOf(String str, int fromIndex) {
  432. 432 return String.indexOf(value, 0, count,
  433. 433 str.toCharArray(), 0, str.length(), fromIndex);
  434. 434 }
  435. 435
  436. 436 public int lastIndexOf(String str) {
  437. 437 return lastIndexOf(str, count);
  438. 438 }
  439. 439
  440. 440 public int lastIndexOf(String str, int fromIndex) {
  441. 441 return String.lastIndexOf(value, 0, count,
  442. 442 str.toCharArray(), 0, str.length(), fromIndex);
  443. 443 }
  444. 444
  445. 445 public AbstractStringBuilder reverse() {
  446. 446 boolean hasSurrogate = false;
  447. 447 int n = count - 1;
  448. 448 for (int j = (n-1) >> 1; j >= 0; --j) {
  449. 449 char temp = value[j];
  450. 450 char temp2 = value[n - j];
  451. 451 if (!hasSurrogate) {
  452. 452 hasSurrogate = (temp >= Character.MIN_SURROGATE && temp <= Character.MAX_SURROGATE)
  453. 453 || (temp2 >= Character.MIN_SURROGATE && temp2 <= Character.MAX_SURROGATE);
  454. 454 }
  455. 455 value[j] = temp2;
  456. 456 value[n - j] = temp;
  457. 457 }
  458. 458 if (hasSurrogate) {
  459. 459 // Reverse back all valid surrogate pairs
  460. 460 for (int i = 0; i < count - 1; i++) {
  461. 461 char c2 = value[i];
  462. 462 if (Character.isLowSurrogate(c2)) {
  463. 463 char c1 = value[i + 1];
  464. 464 if (Character.isHighSurrogate(c1)) {
  465. 465 value[i++] = c1;
  466. 466 value[i] = c2;
  467. 467 }
  468. 468 }
  469. 469 }
  470. 470 }
  471. 471 return this;
  472. 472 }
  473. 473
  474. 474 public abstract String toString();
  475. 475
  476. 476 final char[] getValue() {
  477. 477 return value;
  478. 478 }
  479. 479 }

View Code

StringBuilder源码(基于jdk1.7.40)

  1. 1 package java.lang;
  2. 2
  3. 3 public final class StringBuilder
  4. 4 extends AbstractStringBuilder
  5. 5 implements java.io.Serializable, CharSequence {
  6. 6
  7. 7 static final long serialVersionUID = 4383685877147921099L;
  8. 8
  9. 9 // 构造函数。默认的字符数组大小是16。
  10. 10 public StringBuilder() {
  11. 11 super(16);
  12. 12 }
  13. 13
  14. 14 // 构造函数。指定StringBuilder的字符数组大小是capacity。
  15. 15 public StringBuilder(int capacity) {
  16. 16 super(capacity);
  17. 17 }
  18. 18
  19. 19 // 构造函数。指定字符数组大小=str长度+15,且将str的值赋值到当前字符数组中。
  20. 20 public StringBuilder(String str) {
  21. 21 super(str.length() + 16);
  22. 22 append(str);
  23. 23 }
  24. 24
  25. 25 // 构造函数。指定字符数组大小=seq长度+15,且将seq的值赋值到当前字符数组中。
  26. 26 public StringBuilder(CharSequence seq) {
  27. 27 this(seq.length() + 16);
  28. 28 append(seq);
  29. 29 }
  30. 30
  31. 31 // 追加“对象obj对应的字符串”。String.valueOf(obj)实际上是调用obj.toString()
  32. 32 public StringBuilder append(Object obj) {
  33. 33 return append(String.valueOf(obj));
  34. 34 }
  35. 35
  36. 36 // 追加“str”。
  37. 37 public StringBuilder append(String str) {
  38. 38 super.append(str);
  39. 39 return this;
  40. 40 }
  41. 41
  42. 42 // 追加“sb的内容”。
  43. 43 private StringBuilder append(StringBuilder sb) {
  44. 44 if (sb == null)
  45. 45 return append("null");
  46. 46 int len = sb.length();
  47. 47 int newcount = count + len;
  48. 48 if (newcount > value.length)
  49. 49 expandCapacity(newcount);
  50. 50 sb.getChars(0, len, value, count);
  51. 51 count = newcount;
  52. 52 return this;
  53. 53 }
  54. 54
  55. 55 // 追加“sb的内容”。
  56. 56 public StringBuilder append(StringBuffer sb) {
  57. 57 super.append(sb);
  58. 58 return this;
  59. 59 }
  60. 60
  61. 61 // 追加“s的内容”。
  62. 62 public StringBuilder append(CharSequence s) {
  63. 63 if (s == null)
  64. 64 s = "null";
  65. 65 if (s instanceof String)
  66. 66 return this.append((String)s);
  67. 67 if (s instanceof StringBuffer)
  68. 68 return this.append((StringBuffer)s);
  69. 69 if (s instanceof StringBuilder)
  70. 70 return this.append((StringBuilder)s);
  71. 71 return this.append(s, 0, s.length());
  72. 72 }
  73. 73
  74. 74 // 追加“s从start(包括)到end(不包括)的内容”。
  75. 75 public StringBuilder append(CharSequence s, int start, int end) {
  76. 76 super.append(s, start, end);
  77. 77 return this;
  78. 78 }
  79. 79
  80. 80 // 追加“str字符数组对应的字符串”
  81. 81 public StringBuilder append(char[] str) {
  82. 82 super.append(str);
  83. 83 return this;
  84. 84 }
  85. 85
  86. 86 // 追加“str从offset开始的内容,内容长度是len”
  87. 87 public StringBuilder append(char[] str, int offset, int len) {
  88. 88 super.append(str, offset, len);
  89. 89 return this;
  90. 90 }
  91. 91
  92. 92 // 追加“b对应的字符串”
  93. 93 public StringBuilder append(boolean b) {
  94. 94 super.append(b);
  95. 95 return this;
  96. 96 }
  97. 97
  98. 98 // 追加“c”
  99. 99 public StringBuilder append(char c) {
  100. 100 super.append(c);
  101. 101 return this;
  102. 102 }
  103. 103
  104. 104 // 追加“i”
  105. 105 public StringBuilder append(int i) {
  106. 106 super.append(i);
  107. 107 return this;
  108. 108 }
  109. 109
  110. 110 // 追加“lng”
  111. 111 public StringBuilder append(long lng) {
  112. 112 super.append(lng);
  113. 113 return this;
  114. 114 }
  115. 115
  116. 116 // 追加“f”
  117. 117 public StringBuilder append(float f) {
  118. 118 super.append(f);
  119. 119 return this;
  120. 120 }
  121. 121
  122. 122 // 追加“d”
  123. 123 public StringBuilder append(double d) {
  124. 124 super.append(d);
  125. 125 return this;
  126. 126 }
  127. 127
  128. 128 // 追加“codePoint”
  129. 129 public StringBuilder appendCodePoint(int codePoint) {
  130. 130 super.appendCodePoint(codePoint);
  131. 131 return this;
  132. 132 }
  133. 133
  134. 134 // 删除“从start(包括)到end的内容”
  135. 135 public StringBuilder delete(int start, int end) {
  136. 136 super.delete(start, end);
  137. 137 return this;
  138. 138 }
  139. 139
  140. 140 // 删除“位置index的内容”
  141. 141 public StringBuilder deleteCharAt(int index) {
  142. 142 super.deleteCharAt(index);
  143. 143 return this;
  144. 144 }
  145. 145
  146. 146 // “用str替换StringBuilder中从start(包括)到end(不包括)的内容”
  147. 147 public StringBuilder replace(int start, int end, String str) {
  148. 148 super.replace(start, end, str);
  149. 149 return this;
  150. 150 }
  151. 151
  152. 152 // “在StringBuilder的位置index处插入‘str中从offset开始的内容’,插入内容长度是len”
  153. 153 public StringBuilder insert(int index, char[] str, int offset,
  154. 154 int len)
  155. 155 {
  156. 156 super.insert(index, str, offset, len);
  157. 157 return this;
  158. 158 }
  159. 159
  160. 160 // “在StringBuilder的位置offset处插入obj对应的字符串”
  161. 161 public StringBuilder insert(int offset, Object obj) {
  162. 162 return insert(offset, String.valueOf(obj));
  163. 163 }
  164. 164
  165. 165 // “在StringBuilder的位置offset处插入str”
  166. 166 public StringBuilder insert(int offset, String str) {
  167. 167 super.insert(offset, str);
  168. 168 return this;
  169. 169 }
  170. 170
  171. 171 // “在StringBuilder的位置offset处插入str”
  172. 172 public StringBuilder insert(int offset, char[] str) {
  173. 173 super.insert(offset, str);
  174. 174 return this;
  175. 175 }
  176. 176
  177. 177 // “在StringBuilder的位置dstOffset处插入s”
  178. 178 public StringBuilder insert(int dstOffset, CharSequence s) {
  179. 179 if (s == null)
  180. 180 s = "null";
  181. 181 if (s instanceof String)
  182. 182 return this.insert(dstOffset, (String)s);
  183. 183 return this.insert(dstOffset, s, 0, s.length());
  184. 184 }
  185. 185
  186. 186 // “在StringBuilder的位置dstOffset处插入\'s中从start到end的内容\'”
  187. 187 public StringBuilder insert(int dstOffset, CharSequence s,
  188. 188 int start, int end)
  189. 189 {
  190. 190 super.insert(dstOffset, s, start, end);
  191. 191 return this;
  192. 192 }
  193. 193
  194. 194 // “在StringBuilder的位置Offset处插入b”
  195. 195 public StringBuilder insert(int offset, boolean b) {
  196. 196 super.insert(offset, b);
  197. 197 return this;
  198. 198 }
  199. 199
  200. 200 // “在StringBuilder的位置Offset处插入c”
  201. 201 public StringBuilder insert(int offset, char c) {
  202. 202 super.insert(offset, c);
  203. 203 return this;
  204. 204 }
  205. 205
  206. 206 // “在StringBuilder的位置Offset处插入i”
  207. 207 public StringBuilder insert(int offset, int i) {
  208. 208 return insert(offset, String.valueOf(i));
  209. 209 }
  210. 210
  211. 211 // “在StringBuilder的位置Offset处插入l”
  212. 212 public StringBuilder insert(int offset, long l) {
  213. 213 return insert(offset, String.valueOf(l));
  214. 214 }
  215. 215
  216. 216 // “在StringBuilder的位置Offset处插入f”
  217. 217 public StringBuilder insert(int offset, float f) {
  218. 218 return insert(offset, String.valueOf(f));
  219. 219 }
  220. 220
  221. 221 // “在StringBuilder的位置Offset处插入d”
  222. 222 public StringBuilder insert(int offset, double d) {
  223. 223 return insert(offset, String.valueOf(d));
  224. 224 }
  225. 225
  226. 226 // 返回“str”在StringBuilder的位置
  227. 227 public int indexOf(String str) {
  228. 228 return indexOf(str, 0);
  229. 229 }
  230. 230
  231. 231 // 从fromIndex开始查找,返回“str”在StringBuilder的位置
  232. 232 public int indexOf(String str, int fromIndex) {
  233. 233 return String.indexOf(value, 0, count,
  234. 234 str.toCharArray(), 0, str.length(), fromIndex);
  235. 235 }
  236. 236
  237. 237 // 从后向前查找,返回“str”在StringBuilder的位置
  238. 238 public int lastIndexOf(String str) {
  239. 239 return lastIndexOf(str, count);
  240. 240 }
  241. 241
  242. 242 // 从fromIndex开始,从后向前查找,返回“str”在StringBuilder的位置
  243. 243 public int lastIndexOf(String str, int fromIndex) {
  244. 244 return String.lastIndexOf(value, 0, count,
  245. 245 str.toCharArray(), 0, str.length(), fromIndex);
  246. 246 }
  247. 247
  248. 248 // 反转StringBuilder
  249. 249 public StringBuilder reverse() {
  250. 250 super.reverse();
  251. 251 return this;
  252. 252 }
  253. 253
  254. 254 public String toString() {
  255. 255 // Create a copy, don\'t share the array
  256. 256 return new String(value, 0, count);
  257. 257 }
  258. 258
  259. 259 // 序列化对应的写入函数
  260. 260 private void writeObject(java.io.ObjectOutputStream s)
  261. 261 throws java.io.IOException {
  262. 262 s.defaultWriteObject();
  263. 263 s.writeInt(count);
  264. 264 s.writeObject(value);
  265. 265 }
  266. 266
  267. 267 // 序列化对应的读取函数
  268. 268 private void readObject(java.io.ObjectInputStream s)
  269. 269 throws java.io.IOException, ClassNotFoundException {
  270. 270 s.defaultReadObject();
  271. 271 count = s.readInt();
  272. 272 value = (char[]) s.readObject();
  273. 273 }
  274. 274 }

View Code

 

源码如下(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

 

源码如下(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}
字符编码

 

源码如下(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

 

源码如下(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

 

源码如下(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

 

源码如下(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 

 

下面的示例是整合上面的几个示例的完整的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 }

View Code

 

posted on
2013-11-08 08:33 
如果天空不死 
阅读(55463
评论(1
编辑 
收藏 
举报

版权声明:本文为skywang12345原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/skywang12345/p/string02.html