C++ `
// 右對齊,寬度 10,空格填充
System.out.printf("%10s", "Hello"); // 輸出: " Hello"
// 左對齊
System.out.printf("%-10s", "Hello"); // 輸出: "Hello "
String formatted = String.format("%10s", "Hello"); // 取得字串而非直接輸出
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"
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);` (數值) 或自定義方法 |