我需要生成固定长度的字符串来生成基于字符位置的文件。缺失的字符必须用空格字符填充。
例如,字段 CITY 的固定长度为 15 个字符。对于输入“芝加哥”和“里约热内卢”,输出为
《芝加哥》 “里约热内卢”.
从 Java 1.5 开始,我们可以使用方法 java.lang.String.format(String, Object...) 并使用类似 printf 的格式。
格式字符串
"%1$15s"
可以完成这项工作。其中 1$
表示参数索引,s
表示参数是字符串,15
表示字符串的最小宽度。
把它们放在一起:"%1$15s"
。
对于一般方法,我们有:
public static String fixedLengthString(String string, int length) {
return String.format("%1$"+length+ "s", string);
}
也许有人可以建议另一种格式字符串来用特定字符填充空格?
利用
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
import org.apache.commons.lang3.StringUtils;
String stringToPad = "10";
int maxPadLength = 10;
String paddingCharacter = " ";
StringUtils.leftPad(stringToPad, maxPadLength, paddingCharacter)
在我看来比番石榴好得多。从未见过使用 Guava 的单个企业 Java 项目,但 Apache String Utils 非常常见。
你也可以写一个简单的方法,如下所示
public static String padString(String str, int leng) {
for (int i = str.length(); i <= leng; i++)
str += " ";
return str;
}
Guava Library 有 Strings.padStart 可以完全满足您的需求,以及许多其他有用的实用程序。
这里有一个巧妙的技巧:
// 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()
简单地格式化输出,而不使用任何库。