今天在做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.
下面是實現該需求的兩種方法,利用了java本身的格式化功能。