简体   繁体   English

如何使用指定字符将字符串格式化n次,然后将其附加到另一个字符串?

[英]How to format a string n number of times with a specified character, and then append it to another string?

As the title says, given a string, I would like to pad it (append) with n number of x character. 如标题所示,给定一个字符串,我想用n个x字符填充(附加)。 Please see the below code. 请参见下面的代码。 Is it possible to do that all in one String.format? 是否可以用一种String.format来完成全部操作?

The commented line shows how to append n number of spaces; 注释行显示了如何添加n个空格; I would like to do the exact same thing with a custom character. 我想使用自定义字符做完全相同的事情。

int paddingLength = (int) args.get(0); 
String paddingItem = (String) args.get(1); 

String temp = ((String) row.get(fieldName));


//temp = String.format("%-" + n + "s", s); 

temp = String.format("%-" + paddingLength + "paddingItem", paddingItem + "temp", temp); 

Example: 例:

paddingLength: 5
paddingItem: "_"
temp = "test"

result: "test_____"

Another option is using StringBuilder. 另一种选择是使用StringBuilder。 Example. 例。

int n = 5;
char x = '_';
String temp = "test";
StringBuilder paddedWord = new StringBuilder(temp);
for(int i=0; i<n; i++)
    paddedWord.append(x);

Just remember to cast your StringBuilder back to a String if you are using it elsewhere .toString() 只要记得在其他地方使用.toString()将StringBuilder转换回字符串即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM