Java格式化字符串,左對齊,左補0


今天在做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本身的格式化功能。
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);     
    }     
} 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM