Java中如何填充字符串呢?
下文讲述Java代码中填充字符串的方法分享,如下所示:
实现思路:
使用String.format()方法即可实现填充字符串的操作
例:
package com.java265.other;
public class test {
/*
* java265.com 字符串填充的示例分享
*/
public static void main(String[] args) throws Exception {
String s = "java265.com";
// 填充右边
System.out.println(tianChongYouBian(s, 16));
// 填充左边
System.out.println(tianChongZuoBian(s, 16));
}
public static String tianChongYouBian(String s, int n) {
return String.format("%-" + n + "s", s);
}
public static String tianChongZuoBian(String s, int n) {
return String.format("%" + n + "s", s);
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


