'string'에 해당되는 글 1건

  1. 2009.03.31 String 출력 정렬 구현
잡탕1 - IT2009. 3. 31. 13:38

String format(String str, int length, int alignment) {
    int diff = length - str.length();

    if(diff < 0) return str.substring(0, length);

    char[] source = str.toCharArray();
    char[] result = new char[length];

    for(int i=0; i < result.length; i++)
        result[i] = ' ';

    switch(alignment) {
        case CENTER :
            System.arraycopy(source, 0, result, diff/2, source.length);
            break;
        case RIGHT :
            System.arraycopy(source, 0, result, diff, source.length);
            break;
        case LEFT :
        default :
            System.arraycopy(source, 0, result, 0, source.length);
    }

    return new String(result);
}

length 크기의 result 라는 char 배열을 생성해서 공백으로 채운 다음 System.arraycopy() 를 이용해서 문자열 str의 내용이
담긴 char배열 source를 복사해 넣는다



출처) 'JAVA의 정석' p465, 예제11-60

Posted by pearl짓거리전문