首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java 實現 C++ setw 格式化輸出對齊功能

     編輯:程式設計綜合問答

C++ `setw` 行為回顧

C++ `` 中的 `setw(n)` 設定下一次輸出的最小欄寬,若實際輸出內容寬度不足,預設在左側填充空格(右對齊),常用於表格式輸出。

Java 對應方案

1. `String.format` / `printf`(最接近)

// 右對齊,寬度 10,空格填充
System.out.printf("%10s", "Hello"); // 輸出: "     Hello"

// 左對齊
System.out.printf("%-10s", "Hello"); // 輸出: "Hello     "

2. `String.format` 回傳格式化字串

String formatted = String.format("%10s", "Hello"); // 取得字串而非直接輸出

3. 自定義工具方法(模擬 `setw` 可重用物件)

public class FormatUtils {
    public static String padLeft(String s, int width, char padChar) {
        if (s.length() >= width) return s;
        StringBuilder sb = new StringBuilder(width);
        for (int i = 0; i < width - s.length(); i++) sb.append(padChar);
        sb.append(s);
        return sb.toString();
    }
    public static String padRight(String s, int width, char padChar) {
        if (s.length() >= width) return s;
        StringBuilder sb = new StringBuilder(width);
        sb.append(s);
        for (int i = 0; i < width - s.length(); i++) sb.append(padChar);
        return sb.toString();
    }
}

// 使用
String s = FormatUtils.padLeft("42", 5, ' '); // "   42"
String s2 = FormatUtils.padRight("42", 5, '0'); // "42000"

4. Java 11+ `String.repeat` 簡化填充

String padded = " ".repeat(Math.max(0, width - s.length())) + s; // 左填充

對照表

需求C++Java
右對齊寬度10`cout << setw(10) << val;``System.out.printf("%10s", val);`
左對齊寬度10`cout << left << setw(10) << val;``System.out.printf("%-10s", val);`
指定填充字元`cout << setfill('0') << setw(5) << val;``String.format("%05d", val);` (數值) 或自定義方法

注意事項

  • Java 格式化字串 `%10s` 僅對字串有效,數值請用 `%10d`、`%10f` 等
  • `printf` 直接輸出到標準輸出,`String.format` 回傳字串供進一步處理
  • 若需處理多國語言字元寬度(全形/半形),需使用 `java.text.Bidi` 或第三方庫計算顯示寬度
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved