Skip to content

Instantly share code, notes, and snippets.

@victorwoo
Last active August 29, 2015 14:07
Show Gist options
  • Save victorwoo/af82680d0c435c1e28a3 to your computer and use it in GitHub Desktop.
Save victorwoo/af82680d0c435c1e28a3 to your computer and use it in GitHub Desktop.
import java.io.UnsupportedEncodingException;
public class TextFormat {
public static void main(String[] args) {
try {
String output = String.format("%s%3s", buildSpanAlignLeft("字符串1", 10), "A");
System.out.print(output);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private static int getGbkLength(String str) throws UnsupportedEncodingException {
return str.getBytes("GBK").length;
}
private static String buildSpanAlignLeft(String str, int width) throws UnsupportedEncodingException {
StringBuffer sb = new StringBuffer();
sb.append(str);
for (int i = 0; i < width - getGbkLength(str); i++) {
sb.append(' ');
}
return sb.toString();
}
private static String buildSpanAlignRight(String str, int width) throws UnsupportedEncodingException {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < width - getGbkLength(str); i++) {
sb.append(' ');
}
sb.append(str);
return sb.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment