【发布时间】:2012-11-08 15:34:47
【问题描述】:
我需要生成固定长度的字符串来生成基于字符位置的文件。缺少的字符必须用空格字符填充。
例如,CITY 字段的固定长度为 15 个字符。对于输入“芝加哥”和“里约热内卢”,输出是
“芝加哥” “里约热内卢”。
【问题讨论】:
标签: java string formatting
我需要生成固定长度的字符串来生成基于字符位置的文件。缺少的字符必须用空格字符填充。
例如,CITY 字段的固定长度为 15 个字符。对于输入“芝加哥”和“里约热内卢”,输出是
“芝加哥” “里约热内卢”。
【问题讨论】:
标签: java string formatting
从 Java 1.5 开始,我们可以使用方法java.lang.String.format(String, Object...) 并使用类似 printf 的格式。
格式字符串"%1$15s" 完成这项工作。其中1$表示参数索引,s表示参数是String,15表示String的最小宽度。
把它们放在一起:"%1$15s"。
我们有一个通用的方法:
public static String fixedLengthString(String string, int length) {
return String.format("%1$"+length+ "s", string);
}
也许有人可以建议另一种格式字符串来用特定字符填充空格?
【讨论】:
Maybe someone can suggest another format string to fill the empty spaces with an specific character? - 看看我给出的答案。
1$表示参数索引,15表示宽度
利用String.format 的空格填充并将它们替换为所需的字符。
String toPad = "Apple";
String padded = String.format("%8s", toPad).replace(' ', '0');
System.out.println(padded);
打印000Apple。
更新更高性能的版本(因为它不依赖于String.format),空格没有问题(感谢 Rafael Borja 的提示)。
int width = 10;
char fill = '0';
String toPad = "New York";
String padded = new String(new char[width - toPad.length()]).replace('\0', fill) + toPad;
System.out.println(padded);
打印00New York。
但需要添加检查以防止尝试创建负长度的 char 数组。
【讨论】:
此代码将具有给定数量的字符;右侧填充空格或截断:
private String leftpad(String text, int length) {
return String.format("%" + length + "." + length + "s", text);
}
private String rightpad(String text, int length) {
return String.format("%-" + length + "." + length + "s", text);
}
【讨论】:
对于右垫,您需要String.format("%0$-15s", str)
即- 符号将“右”填充,没有 - 符号将“左”填充
看我的例子:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("================================");
for(int i=0;i<3;i++)
{
String s1=sc.nextLine();
Scanner line = new Scanner( s1);
line=line.useDelimiter(" ");
String language = line.next();
int mark = line.nextInt();;
System.out.printf("%s%03d\n",String.format("%0$-15s", language),mark);
}
System.out.println("================================");
}
}
输入必须是字符串和数字
示例输入:Google 1
【讨论】:
你也可以像下面这样写一个简单的方法
public static String padString(String str, int leng) {
for (int i = str.length(); i <= leng; i++)
str += " ";
return str;
}
【讨论】:
import org.apache.commons.lang3.StringUtils;
String stringToPad = "10";
int maxPadLength = 10;
String paddingCharacter = " ";
StringUtils.leftPad(stringToPad, maxPadLength, paddingCharacter)
比番石榴 imo 好得多。从未见过使用 Guava 的单个企业 Java 项目,但 Apache String Utils 非常普遍。
【讨论】:
Guava Library 有 Strings.padStart 可以完全满足您的需求,以及许多其他有用的实用程序。
【讨论】:
String.format("%15s",s) // pads right
String.format("%-15s",s) // pads left
精彩总结here
【讨论】:
这是一个巧妙的技巧:
// E.g pad("sss","00000000"); should deliver "00000sss".
public static String pad(String string, String pad) {
/*
* Add the pad to the left of string then take as many characters from the right
* that is the same length as the pad.
* This would normally mean starting my substring at
* pad.length() + string.length() - pad.length() but obviously the pad.length()'s
* cancel.
*
* 00000000sss
* ^ ----- Cut before this character - pos = 8 + 3 - 8 = 3
*/
return (pad + string).substring(string.length());
}
public static void main(String[] args) throws InterruptedException {
try {
System.out.println("Pad 'Hello' with ' ' produces: '"+pad("Hello"," ")+"'");
// Prints: Pad 'Hello' with ' ' produces: ' Hello'
} catch (Exception e) {
e.printStackTrace();
}
}
【讨论】:
这是带有测试用例的代码;):
@Test
public void testNullStringShouldReturnStringWithSpaces() throws Exception {
String fixedString = writeAtFixedLength(null, 5);
assertEquals(fixedString, " ");
}
@Test
public void testEmptyStringReturnStringWithSpaces() throws Exception {
String fixedString = writeAtFixedLength("", 5);
assertEquals(fixedString, " ");
}
@Test
public void testShortString_ReturnSameStringPlusSpaces() throws Exception {
String fixedString = writeAtFixedLength("aa", 5);
assertEquals(fixedString, "aa ");
}
@Test
public void testLongStringShouldBeCut() throws Exception {
String fixedString = writeAtFixedLength("aaaaaaaaaa", 5);
assertEquals(fixedString, "aaaaa");
}
private String writeAtFixedLength(String pString, int lenght) {
if (pString != null && !pString.isEmpty()){
return getStringAtFixedLength(pString, lenght);
}else{
return completeWithWhiteSpaces("", lenght);
}
}
private String getStringAtFixedLength(String pString, int lenght) {
if(lenght < pString.length()){
return pString.substring(0, lenght);
}else{
return completeWithWhiteSpaces(pString, lenght - pString.length());
}
}
private String completeWithWhiteSpaces(String pString, int lenght) {
for (int i=0; i<lenght; i++)
pString += " ";
return pString;
}
我喜欢 TDD ;)
【讨论】:
Apache.common.lang3 提供了StringUtils 类,您可以在其中使用以下方法使用您喜欢的字符进行左填充。
StringUtils.leftPad(final String str, final int size, final char padChar);
这里,这是一个静态方法和参数
我们在 StringUtils 类中还有其他方法。
我只是在此处添加 Gradle 依赖项供您参考。
implementation 'org.apache.commons:commons-lang3:3.12.0'
https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.12.0
请查看该类的所有 utils 方法。
https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html
这是来自 jricher 的答案。 Guava 库有 Strings.padStart 可以完全满足您的需求,以及许多其他有用的实用程序。
【讨论】:
public static String padString(String word, int length) {
String newWord = word;
for(int count = word.length(); count < length; count++) {
newWord = " " + newWord;
}
return newWord;
}
【讨论】:
这个简单的功能对我有用:
public static String leftPad(String string, int length, String pad) {
return pad.repeat(length - string.length()) + string;
}
调用:
String s = leftPad(myString, 10, "0");
【讨论】:
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
int s;
String s1 = sc.next();
int x = sc.nextInt();
System.out.printf("%-15s%03d\n", s1, x);
// %-15s -->pads right,%15s-->pads left
}
}
}
使用printf() 来简单地格式化输出而不使用任何库。
【讨论】: