Java knowledge accumulation 1-StringAlign achieves align between left and right text, java1-stringalign

Source: Internet
Author: User

Java knowledge accumulation 1-StringAlign achieves align between left and right text, java1-stringalign

Import java. text .*;
Public class StringAlign extends Format {
Public static final int JUST_LEFT = 'l'; // left-aligned constant
Public static final int JUST_RIGHT = 'R'; // right-aligned constant
Public static final int JUST_CENTER = 'C'; // center constant
Private int just; // The current
Private int maxChars;
Public StringAlign (int maxChars, int just ){
Switch (just ){
Case JUST_CENTER:
Case JUST_LEFT:
Case JUST_RIGHT:
This. just = just;
Break;
Default:
Throw new IllegalArgumentException ("invalid justification arg .");
}
If (maxChars <0 ){
Throw new IllegalArgumentException ("must be a positive number! ");
}
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 there is no space for alignment, the content of the largest row width is returned.
If (wanted. length ()> maxChars ){
Where. append (wanted );
}
Else switch (just ){
Case JUST_RIGHT:
Pad (where, maxChars-wanted.length ());
Where. append (wanted );
Break;
Case JUST_LEFT:
Where. append (wanted );
Pad (where, maxChars-wanted.length ());
Break;
Case JUST_CENTER:
Int startPos = where. length ();
Pad (where, (maxChars-wanted.length ()/2 );
Where. append (wanted );
Pad (where, (maxChars-wanted.length ()/2 );
// Adjusted the integer Error
Pad (where, maxChars-(where. length ()-startPos ));
Break;

}
Return where;
}
Protected final void pad (StringBuffer to, int howpad ){
For (int I = 0; I To. append ('');
}
}
String format (String s ){
Return format (s, new StringBuffer (), null). toString ();
}
@ Override
Public Object parseObject (String source, ParsePosition pos ){
// TODO Auto-generated method stub
Return source;
}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.