今天在做java编程实现邮件发送的时候,遇到邮件发送的内容涉及表格形式的数据,不适合用附件,只能用对齐的形式来展现表格内容,一开始很苦恼,不知道该怎么对齐,最后写了下面这个函数,实现了格式化字符串,左对齐的功能,很简单的函数,却解决了问题。
package com.test; public class TestFormat { TestFormat(){ }; /* c 要填充的字符 * length 填充后字符串的总长度 * content 要格式化的字符串 * 格式化字符串,左对齐 * */ public String flushLeft(char c, long length, String content){ String str = ""; long cl = 0; String cs = ""; if (content.length() > length){ str = content; }else{ for (int i = 0; i < length - content.length(); i++){ cs = cs + c; } } str = content + cs; return str; } public static void main(String[]args){ TestFormat test1 = new TestFormat(); String th1 = test1.flushLeft(' ',6 , "编号"); String th2 = test1.flushLeft(' ',10 , "内容"); String id1 = test1.flushLeft(' ',6 , "12"); String id2 = test1.flushLeft(' ',6 , "1233"); String name1 = test1.flushLeft(' ',10 , "abcde"); String name2 = test1.flushLeft(' ',10 , "1dd"); System.out.print(th1+th2+"\n"); System.out.print(id1+name1+"\n"); System.out.print(id2+name2+"\n"); } }
我们在做数据处理的时候,根据具体要求,可能需要对某些数据,比如数字、字符串,进行格式化输出。其中较为常见的是对数字进行右对齐输出,比如右对齐,左补0.例如:数字12,格式化为0012,数字123,格式化为0123.
package test; public class FormatTest { public static void main(String[] args) { int number1 = 5; int number2 = 0; int number3 = -12; System.out.println("\n------------------ 方法 1 ------------\n"); java.text.DecimalFormat format = new java.text.DecimalFormat("0000"); System.out.println(format.format(number1)); System.out.println(format.format(number2)); System.out.println(format.format(number3)); System.out.println("\n------------------ 方法 2 ------------\n"); // 0 代表前面补充0 // 4 代表长度为4 // d 代表参数为正数型 String str1 = String.format("%04d", number1); String str2 = String.format("%04d", number2); String str3 = String.format("%04d", number3); System.out.println(str1); System.out.println(str2); System.out.println(str3); } }