1. 문자열 변환 후 저장
1) StringBuilder
- StringBuffer() 과 동일하다
- 단, 동기화만 되어 있지 않다
2) StringBuffer
- String 클래스의 인스턴스는 한 번 생성되면 그 값을 읽기만 할 수 있고, 변경할 수 없다(immutable)
- StringBuffer 클래스의 인스턴스는 값을 변경하거나 추가할 수 있다(mutable)
- StringBuffer 클래스는 내부적으로 버퍼(buffer)라고 하는 독립적인 공간을 가진다
- 버퍼 크기의 기본값은 16개의 문자를 저장할 수 있는 크기이다
- 생성자를 통해 버퍼의 크기를 별도로 설정할 수 있지만 인스턴스 생성 시 언제나 설정한 크기보다 16개의 문자를 더 저장할 수 있는 크기로 생성된다
- 문자열 저장(StringBuffer)은 equals 가 아닌 "=="로 대입비교 된다
- equals 를 사용하기 위해서는 String으로 변환 후 비교하여야 한다
2. 문자열 저장(StringBuilder / StringBuffer) 메서드
1) append() 메서드
- 문자열 뒤에 새로 할당된 문자열 값을 추가한다
public class Aaaa {
public static void main(String[] args) {
String abc = "SrtingBuffer";
StringBuffer bcd = new StringBuffer(abc);
StringBuffer cde = bcd.append("append method");
System.out.println(" "+cde);
System.out.print(bcd.append(" result "));
}
}
result
SrtingBufferappend method
SrtingBufferappend method result
2) capacity() 메서드
- 해당 문자열에 할당된 버퍼의 크기를 출력한다
public class Aaaa {
public static void main(String[] args) {
String abc = "SrtingBuffer";
StringBuffer bcd = new StringBuffer(abc);
StringBuffer cde = bcd.append("append method");
System.out.println(bcd.capacity());
System.out.print(cde.capacity());
}
}
result
28
28
//abc 저장공간 12 + 기본 버퍼공간 16
3) delete() 메서드
- 기존 문자열의 지정된 위치에 있는 문자를 삭제한다
- 참조변수의 값은 변경된 문자열로 저장된다
public class Aaaa {
public static void main(String[] args) {
String abc = "StringBuffer";
StringBuffer bcd = new StringBuffer(abc);
StringBuffer cde = bcd.append("delete method");
System.out.println(cde.deleteCharAt(1)); //1번째 문자열 삭제
System.out.println(bcd.delete(3,6)); //1번째 삭제된 상태에서 3번째부터 5번째까지 삭제
System.out.print(cde.deleteCharAt(10)); //삭제 누적된 상태에서 10번째 삭제
}
}
result
SringBufferdelete method
Sriufferdelete method
Sriufferdeete method
4) insert() 메서드
- 기존 문자열의 지정된 위치에 추가 문자열을 삽입한다
- 참조변수의 값은 변경된 문자열로 저장된다
public class Aaaa {
public static void main(String[] args) {
String abc = "String-method";
StringBuffer bcd = new StringBuffer(abc);
StringBuffer cde = bcd.append(" insert method");
System.out.println(bcd.insert(6," + insert + "));
System.out.print(bcd.insert(12,"insert"));
}
}
result
String + insert + -method insert method
String + insinsertert + -method insert method
※ 참조
https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html
StringBuffer (Java Platform SE 7 )
Inserts the string into this character sequence. The characters of the String argument are inserted, in order, into this sequence at the indicated offset, moving up any characters originally above that position and increasing the length of this sequence by
docs.oracle.com
'JAVA' 카테고리의 다른 글
메서드 모음(method) (0) | 2022.05.29 |
---|---|
Java - 상수(Constant), 리터럴(Literal) (0) | 2022.05.29 |
Java - 문자열 분리(StringTokenizer) (0) | 2022.05.29 |
자료구조 - 스택(Stack) (0) | 2022.05.26 |
Java - 문자열(String) (0) | 2022.05.22 |