用空格 (' ') 左填充 Java 中的字符串
让我们先看一个示例,了解如何让字符串向左填充 -
demotext //left padding with spaces 0000000demotext //left padding with 7 zeros
以下是我们的字符串 -
String str = "Jack";
现在使用一个 StringBuilder 对象 -
StringBuilder strBuilder = new StringBuilder();
执行填充并在左边扩展字符串长度。要填充的空间将出现在左边。这里附加空格 -
while (strBuilder.length() + str.length() < 10) {
strBuilder.append(' ');
}以下是向左用空格填充字符串的示例
示例
public class Demo {
public static void main(String[] args) {
String str = "Jack";
StringBuilder strBuilder = new StringBuilder();
// left padding with spaces
while (strBuilder.length() + str.length() < 10) {
strBuilder.append(' ');
}
// append
strBuilder.append(str);
String res = strBuilder.toString();
System.out.println(res);
}
}输出
Jack
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP