gpt4 book ai didi

Java 字符串操作——添加空格或子字符串

转载 作者:行者123 更新时间:2023-12-01 23:11:54 25 4
gpt4 key购买 nike

我正在解构一个 Java 对象,从 getter 中获取所有必需的 String 值,并将所有这些值连接到每个对象的一个​​ String 中。然后我想存储每个字符串是一个

   ArrayList<String>

我将字符串连接成每个对象一个字符串,以便我可以将其打印在 pdf 文档 (pdfbox) 中作为报告...我希望将每一行的格式设置为与表格中相同。例如,无论 String1 的长度是 3 个字符还是 103 个字符,它总是会填充 25 个字符的空间——根据需要,可以使用子字符串来缩小尺寸,也可以使用缓冲空间来增大尺寸。

我的问题是如何有效地做到这一点?对于此示例,假设我要求每个条目的长度为 25 个字符。那么,对于我在下面附加的每个值,如何强制所有条目的长度均为 25 个字符?

    String SPACE="    ";
for(People peeps: list){
builder = new StringBuilder();
name =(peeps.getName());
// if(name.length()>25){name=name.substring(0,25);}
builder.append(name)
.append(SPACE)
.append(peeps.getCode())
.append(SPACE)
.append(peeps.getReference())
.append(SPACE)
.append(peeps.getDate())
.append(SPACE)
.append(peeps.getStatus())
.append(SPACE)
.append(peeps.getValue());

reportList.add(builder.toString());
}

例如

最佳答案

使用Formatter类。

StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb);
sb.append("|");
formatter.format("%-25.25s", "This is some text with more than 25 characters.");
sb.append("|");
formatter.format("%-25.25s", "Some text with less.");
sb.append("|");
formatter.format("%-25.25s", "Some other text.");
sb.append("|");
System.out.println(formatter.toString());

输出:

|This is some text with mo|Some text with less.     |Some other text.         |

关于Java 字符串操作——添加空格或子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21805953/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com