본문 바로가기
java

[java] StringBuffer getChars (Chars to String)

by moonsiri 2020. 10. 31.
728x90
반응형

https://www.tutorialspoint.com/java/lang/stringbuffer_getchars.htm

 

Java.lang.StringBuffer.getChars() Method - Tutorialspoint

Java.lang.StringBuffer.getChars() Method Description The java.lang.StringBuffer.getChars() method copy the characters from this sequence into the destination character array dst. The first character to be copied is at index srcBegin. The last character to

www.tutorialspoint.com

 

StringBuffer에 getChars라는 메소드가 있습니다.

문자열을 char 배열에 넣을때 사용합니다.

 

// java.lang.StringBuffer.getChars() 
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
// new StringBuffer(value).getChars(srcBegin, srcEnd, dst, dstBegin);
// System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
  • srcBegin − This start copying at this offset.
  • srcEnd − This stop copying at this offset.
  • dst − This is the array to copy the data into.
  • dstBegin − This is the offset into dst.

 

 

예시)

StringBuffer sb = new StringBuffer("abcdefghijklmn");
char[] chArr = new char[]{'o','o','o','o','o','o','o','o','o','o','o','o','o','o','o','o'};

// copy the chars from index 5 to index 10 into subarray of chArr
// the offset into destination subarray is set to 3
sb.getChars(5, 10, chArr, 3);

 

위 코드를 실행 한 뒤 chArr를 출력해보면, 'ooofghijoooooooo'가 출력됩니다.

sb의 5번째~9번째 char를 chArr의 3번째 값부터 copy한 것입니다.

만약 string 모두 char[]에 copy하고 싶다면 아래 코드처럼 작성하면 됩니다.

String value = "abcdefghijklmnopqrstuvwxyz";
char chArr[] = new char[value.length()];
char revChArr[] = new char[value.length()];

new StringBuffer.getChars(0, value.length(), chArr, 0);
new StringBuffer.reverse().getChars(0, value.length(), revChArr, 0);  // 역순으로 copy

 

728x90
반응형

댓글