java输出字符串对齐问题
2021-05-06 01:29
标签:返回 mamicode inf main oba 默认 mil microsoft sof
java输出字符串对齐问题 标签:返回 mamicode inf main oba 默认 mil microsoft sof 原文地址:https://www.cnblogs.com/baochao/p/13191217.html输出至文件、文本域时让字符串对齐
代码:
1 public class Align {
2 public static void main(String[] args) {
3 System.out.println("默认输出方式");
4 System.out.println(leftAlign("半角转全角左对齐",20,‘-‘));
5 System.out.println(rightAlign("半角转全角右对齐",20,‘-‘));
6 System.out.println(quanToban(leftAlign("全角转半角左对齐",20,‘-‘)));
7 System.out.println(quanToban(rightAlign("全角转半角右对齐",20,‘-‘)));
8 }
9 //左对齐,半角转全角(原串、希望域宽、填充字符)
10 public static String leftAlign(String str, int len,char c) {
11 char array[] = str.toCharArray();
12 for (int i = 0; i //半角转全角
13 if (array[i] == ‘ ‘) {
14 array[i] = ‘\u3000‘;
15 } else if (array[i] ) {
16 array[i] = (char) (array[i] + 65248);
17 }
18 }
19 int sub = len - str.length();
20 if (sub ) {
21 return new String(array);//大于等于len返回
22 }
23 char[] temp = new char[len];
24 System.arraycopy(array, 0, temp, 0, str.length());
25 for (int j = str.length();j //左对齐右填充
26 if (c == ‘ ‘) {
27 temp[j] = ‘\u3000‘;
28 } else if (c ) {
29 temp[j] = (char) (c + 65248);
30 }
31 }
32 return new String(temp);
33 }
34 //右对齐,半角转全角
35 public static String rightAlign(String str, int len, char c) {
36 char array[] = str.toCharArray();
37 for (int i = 0; i ) {
38 if (array[i] == ‘ ‘) {
39 array[i] = ‘\u3000‘;
40 } else if (array[i] ) {
41 array[i] = (char) (array[i] + 65248);
42 }
43 }
44 int sub = len - str.length();
45 if (sub ) {
46 return new String(array);
47 }
48 char[] temp = new char[len];
49 System.arraycopy(array, 0, temp, sub, str.length());
50 for (int j = 0;j //右对齐左填充
51 if (c == ‘ ‘) {
52 temp[j] = ‘\u3000‘;
53 } else if (c ) {
54 temp[j] = (char) (c + 65248);
55 }
56 }
57 return new String(temp);
58 }
59 //全角转半角,输出默认是半角
60 public static String quanToban(String str) {
61 char array[] = str.toCharArray();
62 for (int i = 0; i ) {
63 if (array[i] == ‘\u3000‘) {
64 array[i] = ‘ ‘;
65 } else if (array[i] > ‘\uFF00‘ && array[i] ) {
66 array[i] = (char) (array[i] - 65248);
67 }
68 }
69 return new String(array);
70 }
71 }
执行结果:
下一篇:javaweb之EL自定义函数