프로그래밍 언어/Java

Java 자료형 - StringBuilder

DevelopJJong 2022. 6. 15. 17:11

StringBuilder은 문자열을 추가할 때 사용하는 자료형이다

 

1.append

 계속해서 문자열을 추가해나갈 수 있다.

public class Main {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        sb.append(1).append("\n");
        sb.append(2).append("\n");
        System.out.println(sb);
    }
}
//
1
2

2.insert

 특정 위치에 원하는 문자열을 삽입할 수 있다.

public class Main {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        sb.append("Hello World is Good").append("\n");
        sb.insert(0,"HIHI ");
        System.out.println(sb);
    }
}
// HIHI Hello World is Good

3.substring

 substring(시작위치, 끝위치) 를 사용하면 시작위치와 끝위치까지에 문자열을 뽑아낸다.

public class Main {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        sb.append("Hello World is Good").append("\n");
        System.out.println(sb.substring(0, 4));
    }
}
// Hell
 
 

3. 부분 문자열