Because accustomed to C # in PadLeft and PadRight, touch Java suddenly lost these two functions, feel awkward, try to implement the two methods.
The string alignment features in String.Format () in Java are as follows:
System.out.println (String.Format ("*%1$-10s*", "Moon")); System.out.println (String.Format ("*%1$10s*", "Moon"));
Output:
The above method can be obtained by simple transformation:
Public Static int Len) { return String.Format ("%1$" + len + "s", s);} Public Static int Len) { return String.Format ("%1$-" + len + "s", s);}
Call the following method:
System.out.println ("*" + Padwhitespaceleft ("Moon", +) + "*"); SYSTEM.OUT.PRINTLN ("*" + Padwhitespaceright ("Moon", 12) + "*");
Results can be obtained:
The above is only to introduce the left and right alignment, the method of filling the white space, but in the actual development process, the simple fill whitespace may not meet the development requirements, for this I would like to do a hardening improvement:
/*** @ Author Yao * @ function string left justified*/ Public StaticString PadLeft (String src,intLenCharch) { intdiff = Len-src.length (); if(diff <= 0) { returnsrc; } Char[] Charr =New Char[Len]; System.arraycopy (Src.tochararray (),0, Charr, 0, Src.length ()); for(inti = Src.length (); i < Len; i++) {Charr[i]=ch; } return NewString (Charr); } /*** @ Author Yao * @ function string Right align*/ Public StaticString PadRight (String src,intLenCharch) { intdiff = Len-src.length (); if(diff <= 0) { returnsrc; } Char[] Charr =New Char[Len]; System.arraycopy (Src.tochararray (),0, Charr, diff, Src.length ()); for(inti = 0; I < diff; i++) {Charr[i]=ch; } return NewString (Charr); }
The calling method is as follows:
System.out.println ("*" + PadLeft ("Moon", +, '-') + "*"); SYSTEM.OUT.PRINTLN ("*" + PadRight ("Moon", 12, '-') + "*");
Output Result:
This way, processing string alignment in Java can be as simple as C #.
The efficiency is also guaranteed.
Implementing String.PadLeft and String.padright in Java