JAVA 類別 - StringBuilder & StringBuffer

String / StringBuilder / StringBuffer

當使用文本數據時,Java提供了三種類別,包括String, StringBufferStringBuilder

當使用大數據來工作時,你應該用StringBufferStringBuilder來優化效率。

三類別差異如下:

  • String 是不可變的。它不允許子類的存在。

  • StringBuffer, StringBuilder 是可變的。

  • StringBuilder和StringBuffer都是一樣的,除了涉及到多線程的使用情況。

    為了處理多線程使用文本,你應該為了防止線程之間沖突而使用StringBuffer。
    要使用一個線程處理的文本,你應該使用StringBuilder。

  • 處理的速度,StringBuilder是最好的,其次是StringBuffer,而最後是String。

JAVA StringBuilder& StringBuffer 類別

當對字符串進行修改的時候,需要使用 StringBuffer 和 StringBuilder 類。

和 String 類不同的是,StringBuffer 和 StringBuilder 類的對象能夠被多次的修改,並且不產生新的未使用對象。

StringBuilder 類在 Java 5 中被提出,它和 StringBuffer 之間的最大不同在於StringBuilder 的方法不是線程安全的(不能同步訪問)。

由於 StringBuilder 相較於 StringBuffer 有速度優勢,所以多數情況下建議使用 StringBuilder 類。

然而在應用程序要求線程安全的情況下,則必須使用 StringBuffer 類。

1
2
3
4
5
6
7
8
9
10
public class Test{
public static void main(String args[]){
StringBuffer sBuffer = new StringBuffer("露西個人網頁網址:");
sBuffer.append("https://");
sBuffer.append(".yujuko");
sBuffer.append(".github");
sBuffer.append(".io");
System.out.println(sBuffer);
}
}

以上實例編譯運行結果如下:

露西個人網頁網址:https://yujuko.github.io/

其他StringBuffer 方法

以下是 StringBuffer 類支持的主要方法:

序號 方法 描述
1 public StringBuffer append(String s) 將指定的字符串追加到此字符序列。
2 public StringBuffer reverse() 將此字符序列用其反轉形式取代。
3 public delete(int start, int end) 移除此序列的子字符串中的字符。
4 public insert(int offset, int i) 將 int 參數的字符串表示形式插入此序列中。
5 replace(int start, int end, String str) 使用給定 String 中的字符替換此序列的子字符串中的字符。

下面的列表裏的方法和 String 類的方法類似:

序號 方法 描述
1 int capacity() 返回當前容量。
2 char charAt(int index) 返回此序列中指定索引處的 char 值。
3 void ensureCapacity(int minimumCapacity) 確保容量至少等於指定的最小值。
4 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) 將字符從此序列覆制到目標字符數組 dst。
5 int indexOf(String str) 返回第一次出現的指定子字符串在該字符串中的索引。
6 int indexOf(String str, int fromIndex) 從指定的索引處開始,返回第一次出現的指定子字符串在該字符串中的索引。
7 int lastIndexOf(String str) 返回最右邊出現的指定子字符串在此字符串中的索引。
8 int lastIndexOf(String str, int fromIndex) 返回 String 對象中子字符串最後出現的位置。
9 int length() 返回長度(字符數)。
10 void setCharAt(int index, char ch) 將給定索引處的字符設置為 ch。
11 void setLength(int newLength) 設置字符序列的長度。
12 CharSequence subSequence(int start, int end) 返回一個新的字符序列,該字符序列是此序列的子序列。
13 String substring(int start) 返回一個新的 String,它包含此字符序列當前所包含的字符子序列。
14 String substring(int start, int end) 返回一個新的 String,它包含此序列當前所包含的字符子序列。
15 String toString() 返回此序列中數據的字符串表示形式。

Leetcode舉例

38. CountAndSay

The count-and-say sequence is the sequence of integers with the first five terms as following:

  1. 1
  2. 11
  3. 21
  4. 1211
  5. 111221
    1 is read off as “one 1” or 11.
    11 is read off as “two 1s” or 21.
    21 is read off as “one 2, then one 1” or 1211.
    Given an integer n, generate the nth term of the count-and-say sequence.
    Note: Each term of the sequence of integers will be represented as a string.

Example 1: Input: 1 Output: "1"

Example 2: Input: 4 Output: "1211"

Solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public String countAndSay(int n) {
StringBuilder curr = new StringBuilder("1");
StringBuilder prev ;
int count;
char num;

for ( int i=1 ; i<n ; i++ ){
prev = curr;
curr = new StringBuilder();
count = 1;
num = prev.charAt(0);

for( int j=1, len = prev.length() ; j<len ; j++ ){
if ( prev.charAt(j) != num ){
curr.append(count).append(num);
count = 1;
num = prev.charAt(j);
}
else{
count ++;
}
}
curr.append(count).append(num);
}return curr.toString();
}
}

125. ValidPalindrome

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.

Example 1: Input: "A man, a plan, a canal: Panama" Output: true

Example 2: Input: "race a car" Output: false

  • Better Solution:

    1
    2
    3
    4
    5
    public boolean isPalindrome(String s) {
    String actual = s.replaceAll("[^A-Za-z0-9]", "").toLowerCase();
    String rev = new StringBuffer(actual).reverse().toString();
    return actual.equals(rev);
    }
  • My Solution

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    public boolean isPalindrome(String s) {

    String str = new String ();
    str = s.toLowerCase().replaceAll("[^(a-zA-Z0-9)]", "").replaceAll("\\pP","");
    //"\\pP"用來去除所有符號,不包括空格

    StringBuffer strb = new StringBuffer(str);
    //需用StringBuffer的reverse方法

    String strv = new String(strb.reverse());
    //需用String的CompareTo方法

    if(str.compareTo(strv)!= 0){
    return false;
    }
    else{
    return true;
    }
    }