2013년 10월 30일 수요일

(Java String)자바에서 문자열의 좌/우 정렬 , 자바강좌, 구로디지털자바교육


(Java String)자바에서 문자열의 좌/우 정렬

 문자열인 텍스트를 자바에서 좌측, 우측, 중앙 정렬하기 위해서는 별도의 클래스를 구현해서 이용해야 하는데 그 예가 아래의 StringAlign.java 입니다.

별도로 만들어진 StringAlign.java라는 텍스트 정렬용 클래스는 Formatter 클래스를 상속하여 문자열의 정렬을 구현했습니다.

-------------------
StringAlign.java
------------------

import java.text.*;


public class StringAlign extends Format {
       
        public static final int JUST_LEFT = 'l';
       
        public static final int JUST_CENTRE = 'c';
       
        public static final int JUST_CENTER = JUST_CENTRE;
       
        public static final int JUST_RIGHT = 'r';

       
        private int just;
       
        private int maxChars;

        public StringAlign(int maxChars, int just) {
                switch(just) {
                case JUST_LEFT:
                case JUST_CENTRE:
                case JUST_RIGHT:
                        this.just = just;
                        break;
                default:
                        throw new IllegalArgumentException("invalid justification arg.");
                }
                if (maxChars < 0) {
                        throw new IllegalArgumentException("maxChars must be positive.");
                }
                this.maxChars = maxChars;
        }

       
        public StringBuffer format(
                Object obj, StringBuffer where, FieldPosition ignore)  {

                String s = (String)obj;
                String wanted = s.substring(0, Math.min(s.length(), maxChars));

                // If no space left for justification, return maxChars' worth */
                if (wanted.length() > maxChars) {
                        where.append(wanted);
                }
                // Else get the spaces in the right place.
                else switch (just) {
                        case JUST_RIGHT:
                                pad(where, maxChars - wanted.length());
                                where.append(wanted);
                                break;
                        case JUST_CENTRE:
                                int startPos = where.length();
                                pad(where, (maxChars - wanted.length())/2);
                                where.append(wanted);
                                pad(where, (maxChars - wanted.length())/2);
                                // Adjust for "rounding error"
                                pad(where, maxChars - (where.length() - startPos));
                                break;
                        case JUST_LEFT:
                                where.append(wanted);
                                pad(where, maxChars - wanted.length());
                                break;
                        }
                return where;
        }

        protected final void pad(StringBuffer to, int howMany) {
                for (int i=0; i<howMany; i++)
                        to.append(' ');
        }

       
        String format(String s) {
                return format(s, new StringBuffer(), null).toString();
        }

       
        public Object parseObject (String source, ParsePosition pos)  {
                return source;
        }

}


-----------------------
StringAlignDemo.java
-----------------------

public class StringAlignDemo {

       
        public static void main(String[] argv) {
                String[] mesg = {"JavaFun", "JavaFun!" };
                for (int i=0; i<mesg.length; i++) {
                        System.out.println("Input String \"" + mesg[i] + "\"");
                        dump(StringAlign.JUST_LEFT, 5,
                                new StringAlign(5, StringAlign.JUST_LEFT).format(mesg[i]));
                        dump(StringAlign.JUST_LEFT, 10,
                                new StringAlign(10, StringAlign.JUST_LEFT).format(mesg[i]));
                        dump(StringAlign.JUST_CENTER, 5,
                                new StringAlign(5, StringAlign.JUST_CENTER).format(mesg[i]));
                        dump(StringAlign.JUST_CENTER, 10,
                                new StringAlign(10, StringAlign.JUST_CENTER).format(mesg[i]));
                        dump(StringAlign.JUST_RIGHT, 5,
                                new StringAlign(5, StringAlign.JUST_RIGHT).format(mesg[i]));
                        dump(StringAlign.JUST_RIGHT, 10,
                                new StringAlign(10, StringAlign.JUST_RIGHT).format(mesg[i]));
                }
        }

        private static void dump(int format, int len, String s) {
                System.out.print((char)format + "[" + len + "]");
                System.out.print(" ==> \"");
                System.out.print(s);
                System.out.print('"');
                System.out.println();
        }
}

[결과]

---------- java ----------
Input String "JavaFun"
l[5] ==> "JavaF"
l[10] ==> "JavaFun   "
c[5] ==> "JavaF"
c[10] ==> " JavaFun  "
r[5] ==> "JavaF"
r[10] ==> "   JavaFun"
Input String "JavaFun!"
l[5] ==> "JavaF"
l[10] ==> "JavaFun!  "
c[5] ==> "JavaF"
c[10] ==> " JavaFun! "
r[5] ==> "JavaF"
r[10] ==> "  JavaFun!"


댓글 없음:

댓글 쓰기