[Java] ๐Ÿ’พ StringBuilder

shrยท2022๋…„ 5์›” 25์ผ
0

Concept

๋ชฉ๋ก ๋ณด๊ธฐ
9/13
post-thumbnail

์‚ฌ์šฉํ•˜๋Š” ์ด์œ 


String์€ ๋ถˆ๋ณ€(immutable) ๊ฐ์ฒด์ด๋‹ค. ์ผ๋ก€๋กœ String str1 = "์‚ฌ๊ณผ";์™€ String str2 = "๋”ธ๊ธฐ";๋ผ๋Š” 2 ๊ฐœ์˜ ๊ฐ์ฒด๊ฐ€ ์žˆ์„ ๋•Œ, str1 + str2;์™€ ๊ฐ™์€ ์—ฐ์‚ฐ์„ ํ•˜๊ฒŒ ๋˜๋ฉด ์ƒˆ๋กœ์šด ๋ฌธ์ž์—ด์ด ๋˜ ์ƒ์„ฑ๋˜๊ณ  ์ด์ „์˜ ๋ฌธ์ž์—ด์€ ๊ฐ€๋น„์ง€ ์ฝœ๋ ‰ํ„ฐ๋กœ ๋“ค์–ด๊ฐ„๋‹ค. ๋งŽ์€ ๋ฌธ์ž์—ด์„ ์—ฐ๊ฒฐํ•˜๋ฉด ๊ทธ๋งŒํผ ๋งŽ์€ ์ค‘๊ฐ„ ๋ฌธ์ž์—ด ๊ฐ์ฒด๊ฐ€ ์ƒ์„ฑ๋œ๋‹ค. ๋”ฐ๋ผ์„œ ์ด๋Ÿฌํ•œ ์—ฐ์‚ฐ์ด ๋งŽ์•„์ง„๋‹ค๋ฉด ์„ฑ๋Šฅ์ ์œผ๋กœ ์ข‹์ง€ ์•Š๋‹ค.

๊ทธ๋ž˜์„œ StringBuilder๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค. StringBuilder๋Š” String๊ณผ ๋ฌธ์ž์—ด์„ ๋”ํ•  ๋•Œ ์ƒˆ๋กœ์šด ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ ๊ธฐ์กด์˜ ๋ฐ์ดํ„ฐ์— ๋”ํ•˜๋Š” ๋ฐฉ์‹์ด๋‹ค. ๋”ฐ๋ผ์„œ ์†๋„๋„ ๋น ๋ฅด๋ฉฐ ์ƒ๋Œ€์ ์œผ๋กœ ๋ถ€ํ•˜๊ฐ€ ์ ๋‹ค. ๊ธด ๋ฌธ์ž์—ด์„ ๋”ํ•˜๋Š” ๊ฒฝ์šฐ์—๋Š” StringBuilder๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์ข‹๋‹ค.


์‚ฌ์šฉ๋ฒ•


public class Main
{
    public static void main(String[] args)
    {
		StringBuilder sb = new StringBuilder(); 		/* ๋ฌธ์ž์—ด์„ ์ธ์ž๋กœ ๋ฐ”๋กœ ๋„ฃ์–ด๋„ ๋œ๋‹ค. */
        sb.append("์‚ฌ๊ณผ, ").append("๋”ธ๊ธฐ");
        String str = sb.toString();
        System.out.println(sb.toString());				/* ์‚ฌ๊ณผ, ๋”ธ๊ธฐ */
        System.out.println(str);							/* ์‚ฌ๊ณผ, ๋”ธ๊ธฐ */
    }
}

StringBuilder ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๊ณ , append()๋กœ ์—ฐ๊ฒฐํ•˜๋ ค๋Š” ๋ฌธ์ž์—ด์„ ๋„ฃ๋Š”๋‹ค. ์ถœ๋ ฅํ•  ๋•Œ๋‚˜, String ๋ณ€์ˆ˜์— ๋„ฃ๊ณ ์ž ํ•  ๋•Œ๋Š” toString()์„ ๋ถ™์—ฌ ์ฃผ์–ด์•ผ ํ•œ๋‹ค.


๋‹ค์–‘ํ•œ ๋ฉ”์†Œ๋“œ


public class Main
{
	public static void main(String[] args) 
	{
		StringBuilder sb = new StringBuilder();
		sb.append("์‚ฌ๊ณผ ").append("๋”ธ๊ธฐ ").append("ํ† ๋งˆํ†  ").append("์•ต๋‘ ").append("๋ง๊ณ !!");
		System.out.println(sb.toString()); 		/* ์‚ฌ๊ณผ ๋”ธ๊ธฐ ํ† ๋งˆํ†  ์•ต๋‘ ๋ง๊ณ !! */
		sb.insert(3, "๋ฐ”๋‚˜๋‚˜ ");
		System.out.println(sb.toString()); 		/* ์‚ฌ๊ณผ ๋ฐ”๋‚˜๋‚˜ ๋”ธ๊ธฐ ํ† ๋งˆํ†  ์•ต๋‘ ๋ง๊ณ !! */
		sb.delete(0, 3);
		System.out.println(sb.toString()); 		/* ๋ฐ”๋‚˜๋‚˜ ๋”ธ๊ธฐ ํ† ๋งˆํ†  ์•ต๋‘ ๋ง๊ณ !! */
		System.out.println(sb.indexOf("์•ต๋‘"));			/* 11 */
		System.out.println(sb.substring(11, 13));			/* ์•ต๋‘ */
		System.out.println(sb.length());						/* 18 */
		System.out.println(sb.replace(11, 13, "์ฒด๋ฆฌ")); 	/* ๋ฐ”๋‚˜๋‚˜ ๋”ธ๊ธฐ ํ† ๋งˆํ†  ์ฒด๋ฆฌ ๋ง๊ณ !! */
		System.out.println(sb.reverse());					/* !!๊ณ ๋ง ๋ฆฌ์ฒด ํ† ๋งˆํ†  ๊ธฐ๋”ธ ๋‚˜๋‚˜๋ฐ” */
	}

}

์ฐธ๊ณ  ์ž๋ฃŒ


์ž๋ฐ” StringBuilder ์‚ฌ์šฉ๋ฒ• ๋ฐ ์‚ฌ์šฉํ•˜๋Š” ์ด์œ 
[JAVA] StringBuilder๋ž€? StringBuilder ์‚ฌ์šฉ๋ฒ•
์ž๋ฐ” StringBuffer, StringBuilder ๊ฐœ๋…๋ถ€ํ„ฐ ์‚ฌ์šฉ๋ฒ•๊นŒ์ง€

profile
๋ชปํ•˜๋‹ค ๋ณด๋ฉด ์ž˜ํ•˜๊ฒŒ ๋˜๋Š” ๊ฑฐ์•ผ ๏ฝฅแด—๏ฝฅฬฅฬฅฬฅ

0๊ฐœ์˜ ๋Œ“๊ธ€