StringBuilder()的使用

小倫的筆記
Nov 6 · 4 min read

StringBuilder跟StringBuffer 是一個classes類似String的classes但是比string還要更有可變動性。

也就是說StringBuilder和StringBuffer相較於String可以有更多空間活用。當我們宣告String時,要在裡面更改字串會比較麻煩。但是StringBuilder就很方便。用下面的例子來一一介紹。

只是StringBuilder和StringBuffer在運作上有些不同,但是他們的method可以說是一樣的,所以如果要換一個用法的話,如下面範例:

首先我們要使用的話,要先建一個StringBuilder的物件

import java.lang.StringBuilder;

StringBuilder str = new StringBuilder();

另一種寫法:

import java.lang.StringBuffer;

StringBuffer str = new StringBuffer();


使用它內部所給的一些method:

str.append() — 放入資料進去

放進去的資料可以是不同的形態:int, float, boolean, char, char[], String, double, long (可以自己試試看其他型態)

str.append("Welcome");
str.append(" to");
str.append("My blog");

str.insert() — 插入資料進去

str.insert(Index, “String”);

*注意:假設我字串目前是”Welcome”,只到6的話,我不可以寫str.insert(8, “xxx”),因為這樣會超出字串原本的所到的長度,會出現error。

Example:

str.append("Welcome"); // 0 ~ 6str.insert(6, "yoyoman"); 
// output : Welcomyoyomane 代表是把字串插入在6前面
str.insert(7, "yoyoman");
//
output : Welcomeyoyoman 把字串插入在7前面
str.insert(8, "yoyoman");
// output: error

str.delete() — 刪除字串

— str.delete(startIndex, endIndex)

*假設我要刪除第11~14行的字,裡面要這樣寫str.delete(11, 15, “xxx”);

*注意到我的endIndex是15(same as below “replace method”)

str.append("Welcome to my blog");
str.delete(11, 13); // delete "my"
// output: Welcome to blog

str.deleteCharAt() — 刪除特定字元

str.append("Welcome to my blog");
str.deleteCharAt(11); // delete "my"
// output: Welcome to y blog

str.reverse() — 翻轉字串

str.append("Welcome to my blog");
str.reverse();
// output: golb ym ot emocleW

str.replace(startIndex, endIndex, String) — 取代字串

*假設我要取代第11~14行的字,裡面要這樣寫str.replace(11, 15, “xxx”);

*注意到我的endIndex是15

str.setCharAt() — 將特定字元取代

str.append("Welcome to my blog");
str.setChar(11, 'M');
// output: Welcome to My blog

toString() — 回傳整串字串回去(用於寫在method時要呼叫回去)

capacity() — 整個字串的大小

假設是17個字,一個char是2byte所以大小是2 * 17 = 34

charAt(int Index) — 回傳字串上某位子的字元

str.append("Welcome to my blog");
char a = str.charAt(0);
// a == W

length() — 回傳字串的長度

假設是17個字,長度就是17

substring(Index) — 回傳string的次集合

substring(startIndex, endIndex)

— 這裡的endIndex一樣是跟replace() “endIndex -1"

str.append("Welcome to my blog");
String s = str.substring(7);
// output: to my blog
s = str.substring(8 , 11); // to應該是8~10 //但是規定就是要寫到11
// output: to
小倫的筆記

Written by

目前資工系大二,想要將自己所學到的東西,吸收過後再用自己的方式傳達出去。順便當成自己的學習筆記。

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade