JAVA :: StringBuilder

s_omiยท2022๋…„ 7์›” 23์ผ
0

JAVA (์ž๋ฐ”)

๋ชฉ๋ก ๋ณด๊ธฐ
46/62
post-thumbnail
post-custom-banner

๐Ÿ“ StringBuilder

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

๐Ÿ’ก ์ฃผ์š” ๋ฉ”์†Œ๋“œ

๋ฉ”์†Œ๋“œ์„ค๋ช…
.append()๋ฌธ์ž์—ด์„ ์ถ”๊ฐ€
.insert(int offset, String str)offset ์œ„์น˜์— str์„ ์ถ”๊ฐ€
.replace(int first, int )์ฒซ๋ฒˆ์งธ์™€ ๋‘๋ฒˆ์งธ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ๋ฐ›๋Š” ์ˆซ์ž ์ธ๋ฑ์Šค์— ์œ„์น˜ํ•œ ๋ฌธ์ž์—ด์„ ๋Œ€์ฒด
.substring(int start, (int end))์ธ๋ฑ์‹ฑ. ํŒŒ๋ผ๋ฏธํ„ฐ๊ฐ€ ํ•˜๋‚˜๋ผ๋ฉด ํ•ด๋‹น ์ธ๋ฑ์Šค๋ถ€ํ„ฐ ๋๊นŒ์ง€, ๋‘๊ฐœ๋ผ๋ฉด ์‹œ์ž‘์ ๊ณผ ๋์ -1 ๊นŒ์ง€ ์ธ๋ฑ์‹ฑ
.deleteCharAt(int index)์ธ๋ฑ์Šค์— ์œ„์น˜ํ•œ ๋ฌธ์ž ํ•˜๋‚˜๋ฅผ ์‚ญ์ œ
.delete(int start, int end)start ๋ถ€ํ„ฐ end-1 ๊นŒ์ง€์˜ ๋ฌธ์ž๋ฅผ ์‚ญ์ œ
.toString()String์œผ๋กœ ๋ณ€ํ™˜ํ•œ๋‹ค.
.reverse()ํ•ด๋‹น ๋ฌธ์ž ์ „์ฒด๋ฅผ ๋’ค์ง‘๋Š”๋‹ค.
.setCharAt(int index, String s)index ์œ„์น˜์˜ ๋ฌธ์ž๋ฅผ s๋กœ ๋ณ€๊ฒฝ
.setLength(int len)๋ฌธ์ž์—ด ๊ธธ์ด ์กฐ์ •, ํ˜„์žฌ ๋ฌธ์ž์—ด๋ณด๋‹ค ๊ธธ๊ฒŒ ์กฐ์ •ํ•˜๋ฉด ๊ณต๋ฐฑ์œผ๋กœ ์ฑ„์›Œ์ง, ํ˜„์žฌ ๋ฌธ์ž์—ด๋ณด๋‹ค ์งง๊ฒŒ ์กฐ์ •ํ•˜๋ฉด ๋‚˜๋จธ์ง€ ๋ฌธ์ž๋Š” ์‚ญ์ œ
.trimToSize()๋ฌธ์ž์—ด์ด ์ €์žฅ๋œ char[] ๋ฐฐ์—ด ์‚ฌ์ด์ฆˆ๋ฅผ ํ˜„์žฌ ๋ฌธ์ž์—ด ๊ธธ์ด์™€ ๋™์ผํ•˜๊ฒŒ ์กฐ์ •, String ํด๋ž˜์Šค์˜ trim()์ด ์•ž ๋’ค ๊ณต๋ฐฑ์„ ์ œ๊ฑฐํ•˜๋Š” ๊ฒƒ๊ณผ ๊ฐ™์ด ๊ณต๋ฐฑ ์‚ฌ์ด์ฆˆ๋ฅผ ์ œ๊ณตํ•˜๋Š” ๊ฒƒ, ๋ฐฐ์—ด์˜ ๋‚จ๋Š” ์‚ฌ์ด์ฆˆ๋Š” ๊ณต๋ฐฑ์ด๋ฏ€๋กœ, ๋ฌธ์ž์—ด ๋’ท๋ถ€๋ถ„์˜ ๊ณต๋ฐฑ์„ ๋ชจ๋‘ ์ œ๊ฑฐํ•ด์ค€๋‹ค๊ณ  ๋ณด๋ฉด ๋จ

โ–ถ ์˜ˆ์‹œ

public static void main(String[] args) {
    StringBuilder sb = new StringBuilder("JA");

    sb.append("VA");
    System.out.println(sb);   // JAVA

    sb.deleteCharAt(2);
    System.out.println(sb);   // JAV

    sb.insert(2, "JIM");
    System.out.println(sb);   // JAJIMA

    System.out.println(sb.reverse());       // AMIJAJ
    System.out.println(sb.substring(0,3));  // AMI

    System.out.println(sb.length());    // 6
    System.out.println(sb.capacity());  // 18

    sb.trimToSize();
    System.out.println(sb.capacity());  //6
}

profile
๊ณต๋ถ€ํ•œ ๊ฑฐ ์˜ฌ๋ ค์š” :)
post-custom-banner

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