๊ด€๋ฆฌ ๋ฉ”๋‰ด

ruriruriya

[JAVA] ์ž๋ฐ” ์ŠคํŠธ๋ง๋ฒ„ํผ(StringBuffer) ๋ณธ๋ฌธ

๐ŸชJava

[JAVA] ์ž๋ฐ” ์ŠคํŠธ๋ง๋ฒ„ํผ(StringBuffer)

๋ฃจ๋ฆฌ์•ผใ…‘ 2023. 11. 13. 16:24
๋ฐ˜์‘ํ˜•

์‚ฌ์ง„: Unsplash ์˜ Alex Bachor

์ž๋ฐ” StringBuffer๋Š” ๋ฌธ์ž์—ด์„ ์ถ”๊ฐ€ํ•˜๊ฑฐ๋‚˜ ๋ณ€๊ฒฝํ•  ๋•Œ ์“ฐ๋Š” ์ž๋ฃŒํ˜•์œผ๋กœ
๋‹ค์–‘ํ•œ ๋ฉ”์†Œ๋“œ๋ฅผ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

append ๋ฉ”์†Œ๋“œ

append ๋ฉ”์†Œ๋“œ๋Š” ๋ฌธ์ž์—ด์„ ์ถ”๊ฐ€ํ•ด์ฃผ๋Š” ์—ญํ• ์„ ํ•œ๋‹ค.
String ์ž๋ฃŒํ˜•์œผ๋กœ ์ถœ๋ ฅํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด toString() ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•ด์„œ ๋ณ€๊ฒฝํ•ด์•ผ ํ•œ๋‹ค.

String ์ž๋ฃŒํ˜•์€ ๊ฐ’์ด ํ•œ๋ฒˆ ์ƒ์„ฑ๋˜๋ฉด ๋ฐ”๊ฟ€ ์ˆ˜ ์—†์ง€๋งŒ StringBuffer ์ž๋ฃŒํ˜•์€ ๊ฐ’์„ ๋ณ€๊ฒฝ์ด ๊ฐ€๋Šฅํ•ด ์ด๋ฏธ ์ƒ์„ฑ๋œ ๊ฐ’์„ ์–ธ์ œ๋“ ์ง€ ์ˆ˜์ •ํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ์žฅ์ ์ด ์žˆ๋‹ค.

* ์ด๋ฎคํ„ฐ๋ธ”(immutable)ํ•˜๋‹ค : ๊ฐ’์„ ๋ณ€๊ฒฝํ•  ์ˆ˜ ์—†์Œ.
* ๋ฎคํ„ฐ๋ธ”(mutable)ํ•˜๋‹ค : ๋ณ€๊ฒฝํ•  ์ˆ˜ ์žˆ์Œ.

StringBuffer sb = new StringBuffer();
sb.append("Hello");
sb.append(" I");
sb.append(" Miss");
sb.append(" You");
String result = sb.toString();
System.out.println(result);
// "Hello I Miss You" ์ถœ๋ ฅ

ํ•˜์ง€๋งŒ Stringbuffer๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ๋ฌด์กฐ๊ฑด ์ข‹์€ ๊ฒƒ์ด ์•„๋‹ˆ๋‹ค.
์ƒํ™ฉ๋งˆ๋‹ค ๋‹ค๋ฅด์ง€๋งŒ StringBuffer๋Š” String๋ณด๋‹ค ๋ฌด๊ฒ๊ธฐ ๋•Œ๋ฌธ์— ๊ฐ์ฒด ์ƒ์„ฑ์‹œ String์„ ์‚ฌ์šฉํ•  ๋•Œ๋ณด๋‹ค ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ๋Ÿ‰๋„ ๋งŽ๊ณ  ์†๋„๋„ ๋Š๋ฆฐ ๋‹จ์ ์ด ์žˆ๋‹ค. ๊ทธ๋ž˜์„œ ์ˆ˜์ •์‚ฌํ•ญ์ด ์ˆ˜์‹œ๋กœ ์žˆ์„ ๋• StringBuffer๋ฅผ ์ˆ˜์ •์‚ฌํ•ญ์ด ์ ์„ ๊ฒƒ์ด๋ฉด String์„ ์ƒํ™ฉ์— ๋งž๊ฒŒ ์“ฐ๋Š” ๊ฒƒ์ด ์ข‹๋‹ค.

 

insert ๋ฉ”์†Œ๋“œ

insert ๋ฉ”์†Œ๋“œ๋Š” ํŠน์ • ์œ„์น˜์— ์›ํ•˜๋Š” ๋ฌธ์ž์—ด์„ ์‚ฝ์ž…ํ•  ์ˆ˜ ์žˆ๋‹ค.

insert(์œ„์น˜์ธ๋ฑ์Šค,"์‚ฝ์ž…ํ•  ๋ฌธ์ž์—ด")

StringBuffer sb - new StringBuffer();
sb.append("I'm ruri");
sb.append(0,"Hello, ");
System.out.println(sb.toString()); // "Hello, I'm ruri" ์ถœ๋ ฅ

 

substring ๋ฉ”์†Œ๋“œ

substring ๋ฉ”์†Œ๋“œ๋Š” String ์ž๋ฃŒํ˜•์˜ substring ๋ฉ”์†Œ๋“œ์™€ ๋™์ผํ•˜๊ฒŒ ์ž‘๋™ํ•œ๋‹ค.
StringBuffer ๊ฐ์ฒด์˜ ์‹œ์ž‘ ์œ„์น˜์—์„œ ๋ ์œ„์น˜๊นŒ์ง€์˜ ๋ฌธ์ž๋ฅผ ๋ฝ‘์•„๋‚ด๋Š” ์—ญํ™œ์„ ํ•œ๋‹ค.
์ด ๋•Œ ๋ ์œ„์น˜ ์ธ๋ฑ์Šค ์ „๊นŒ์ง€ ์ถœ๋ ฅํ•œ๋‹ค.

substring(์‹œ์ž‘ ์œ„์น˜ ์ธ๋ฑ์Šค, ๋ ์œ„์น˜ ์ธ๋ฑ์Šค)

StringBuffer sb = new StringBuffer();
sb.append("Hello, I'm ruri");
System.out.println(sb.snbstring(0,4)); //Hell ์ถœ๋ ฅ

 

๋ฐ˜์‘ํ˜•