理解StringBuilder
Posted liuliu5151
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了理解StringBuilder相关的知识,希望对你有一定的参考价值。
StringBuilder objects are like String objects, except that they can be modified. Internally, these objects are treated like variable-length arrays that contain a sequence of characters. At any point, the length and content of the sequence can be changed through method invocations.
Strings should always be used unless string builders offer an advantage in terms of simpler code (see the sample program at the end of this section) or better performance. For example, if you need to concatenate a large number of strings, appending to a StringBuilder object is more efficient.
在[leetcode]6. ZigZag Conversion字符串Z形排列 中,我们对每一个row,都要新建一个StringBuilder来存该row的info
代码写出来如下,发现StringBuilder 被当做array来使用,所以StringBuilder[]相当于array of array
1 class Solution { 2 public String convert(String s, int numRows) { 3 char[] c = s.toCharArray(); 4 int len = c.length; 5 StringBuilder[] sb = new StringBuilder[numRows]; 6 // 要按row来进行遍历,每一个row先allocate一个StringBuilder 7 for (int i = 0; i < sb.length; i++) { 8 sb[i] = new StringBuilder(); 9 } 10 11 int idx = 0; //用来扫String s 12 while (idx < len) { 13 for (int i = 0; i < numRows && idx < len; i++) { 14 sb[i].append(c[idx++]); 15 } 16 // sloping side 17 for (int i = numRows - 2; i >= 1 && idx < len; i--) { 18 sb[i].append(c[idx++]); 19 } 20 21 } 22 //从sb[0]开始,将sb[1], sb[2], sb[3]... append到一个StringBuilder 23 for (int i = 1; i < sb.length; i++) { 24 sb[0].append(sb[i]); 25 } 26 return sb[0].toString(); 27 } 28 }
以上是关于理解StringBuilder的主要内容,如果未能解决你的问题,请参考以下文章
简单的理解 StringBuffer/StringBuilder/String 的区别
怎么理解Stringbuffer 是线程安全的 stringbuilder是线程不安全的