有一些简单的方法来填充字符串在Java?
似乎是一些应该在一些stringutil类API,但我找不到任何东西,这样做。
有一些简单的方法来填充字符串在Java?
似乎是一些应该在一些stringutil类API,但我找不到任何东西,这样做。
Apache StringUtils有几个方法:leftPad, rightPad, center和repeat。
但是请注意,正如其他人在这个回答中提到和演示的那样,JDK中的String.format()和Formatter类是更好的选择。使用它们而不是公共代码。
看看org.apache.commons.lang.StringUtils#rightPad(String str, int size, char padChar)。
但算法非常简单(填充到字符大小):
public String pad(String str, int size, char padChar)
{
StringBuilder padded = new StringBuilder(str);
while (padded.length() < size)
{
padded.append(padChar);
}
return padded.toString();
}
你可以通过保留填充数据来减少每次调用的开销,而不是每次都重新构建:
public class RightPadder {
private int length;
private String padding;
public RightPadder(int length, String pad) {
this.length = length;
StringBuilder sb = new StringBuilder(pad);
while (sb.length() < length) {
sb.append(sb);
}
padding = sb.toString();
}
public String pad(String s) {
return (s.length() < length ? s + padding : s).substring(0, length);
}
}
作为一种替代方法,您可以将结果长度作为pad(…)方法的参数。在这种情况下,在该方法中而不是在构造函数中调整隐藏填充。
(提示:为了获得额外的学分,让它是线程安全的!: -)
formatter会做左右填充。不需要奇怪的第三方依赖关系(您会为如此微不足道的事情添加它们吗)。
[我省略了细节,把这篇文章做成“社区维基”,因为这不是我需要的东西。]
从Java 1.5开始,string. format()可以用于左/右填充给定的字符串。
public static String padRight(String s, int n) {
return String.format("%-" + n + "s", s);
}
public static String padLeft(String s, int n) {
return String.format("%" + n + "s", s);
}
...
public static void main(String args[]) throws Exception {
System.out.println(padRight("Howto", 20) + "*");
System.out.println(padLeft("Howto", 20) + "*");
}
输出为:
Howto *
Howto*
你可以使用内置的StringBuilder append()和insert()方法, 对于可变字符串长度的填充:
AbstractStringBuilder append(CharSequence s, int start, int end) ;
例如:
private static final String MAX_STRING = " "; //20 spaces
Set<StringBuilder> set= new HashSet<StringBuilder>();
set.add(new StringBuilder("12345678"));
set.add(new StringBuilder("123456789"));
set.add(new StringBuilder("1234567811"));
set.add(new StringBuilder("12345678123"));
set.add(new StringBuilder("1234567812234"));
set.add(new StringBuilder("1234567812222"));
set.add(new StringBuilder("12345678122334"));
for(StringBuilder padMe: set)
padMe.append(MAX_STRING, padMe.length(), MAX_STRING.length());
我知道这个线程有点老了,最初的问题是为了一个简单的解决方案,但如果它应该是真的很快,你应该使用字符数组。
public static String pad(String str, int size, char padChar)
{
if (str.length() < size)
{
char[] temp = new char[size];
int i = 0;
while (i < str.length())
{
temp[i] = str.charAt(i);
i++;
}
while (i < size)
{
temp[i] = padChar;
i++;
}
str = new String(temp);
}
return str;
}
格式化程序解决方案不是最佳的。仅仅构建格式字符串就会创建2个新字符串。
Apache的解决方案可以通过用目标大小初始化sb来改进,从而替换下面的内容
StringBuffer padded = new StringBuffer(str);
与
StringBuffer padded = new StringBuffer(pad);
padded.append(value);
会阻止某人内部缓冲的增长。
我花了一点时间才想明白。 真正的关键是阅读Formatter文档。
// Get your data from wherever.
final byte[] data = getData();
// Get the digest engine.
final MessageDigest md5= MessageDigest.getInstance("MD5");
// Send your data through it.
md5.update(data);
// Parse the data as a positive BigInteger.
final BigInteger digest = new BigInteger(1,md5.digest());
// Pad the digest with blanks, 32 wide.
String hex = String.format(
// See: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html
// Format: %[argument_index$][flags][width]conversion
// Conversion: 'x', 'X' integral The result is formatted as a hexadecimal integer
"%1$32x",
digest
);
// Replace the blank padding with 0s.
hex = hex.replace(" ","0");
System.out.println(hex);
如此:
"".format("%1$-" + 9 + "s", "XXX").replaceAll(" ", "0")
它会用空白填充你的字符串XXX,最多9个字符。在此之后,所有空格将被替换为0。你可以把空格和0改为任何你想要的…
填充到10个字符:
String.format("%10s", "foo").replace(' ', '*');
String.format("%-10s", "bar").replace(' ', '*');
String.format("%10s", "longer than 10 chars").replace(' ', '*');
输出:
*******foo
bar*******
longer*than*10*chars
密码字符显示“*”:
String password = "secret123";
String padded = String.format("%"+password.length()+"s", "").replace(' ', '*');
输出与密码字符串长度相同:
secret123
*********
public static String padLeft(String in, int size, char padChar) {
if (in.length() <= size) {
char[] temp = new char[size];
/* Llenado Array con el padChar*/
for(int i =0;i<size;i++){
temp[i]= padChar;
}
int posIniTemp = size-in.length();
for(int i=0;i<in.length();i++){
temp[posIniTemp]=in.charAt(i);
posIniTemp++;
}
return new String(temp);
}
return "";
}
下面是另一种向右填充的方法:
// put the number of spaces, or any character you like, in your paddedString
String paddedString = "--------------------";
String myStringToBePadded = "I like donuts";
myStringToBePadded = myStringToBePadded + paddedString.substring(myStringToBePadded.length());
//result:
myStringToBePadded = "I like donuts-------";
在番石榴中,这很简单:
Strings.padStart("string", 10, ' ');
Strings.padEnd("string", 10, ' ');
一个简单的解决方案是:
package nl;
public class Padder {
public static void main(String[] args) {
String s = "123" ;
System.out.println("#"+(" " + s).substring(s.length())+"#");
}
}
public static String LPad(String str, Integer length, char car) {
return (str + String.format("%" + length + "s", "").replace(" ", String.valueOf(car))).substring(0, length);
}
public static String RPad(String str, Integer length, char car) {
return (String.format("%" + length + "s", "").replace(" ", String.valueOf(car)) + str).substring(str.length(), length + str.length());
}
LPad("Hi", 10, 'R') //gives "RRRRRRRRHi"
RPad("Hi", 10, 'R') //gives "HiRRRRRRRR"
RPad("Hi", 10, ' ') //gives "Hi "
RPad("Hi", 1, ' ') //gives "H"
//etc...
简单的东西:
该值应该是字符串。如果不是,就转换成字符串。比如"" + 123或Integer.toString(123)
// let's assume value holds the String we want to pad
String value = "123";
子字符串从值length char索引开始,直到填充的结束长度:
String padded="00000000".substring(value.length()) + value;
// now padded is "00000123"
更精确的
垫:
String padded = value + ("ABCDEFGH".substring(value.length()));
// now padded is "123DEFGH"
垫左:
String padString = "ABCDEFGH";
String padded = (padString.substring(0, padString.length() - value.length())) + value;
// now padded is "ABCDE123"
很多人都有一些非常有趣的技巧,但我喜欢保持简单,所以我用这个:
public static String padRight(String s, int n, char padding){
StringBuilder builder = new StringBuilder(s.length() + n);
builder.append(s);
for(int i = 0; i < n; i++){
builder.append(padding);
}
return builder.toString();
}
public static String padLeft(String s, int n, char padding) {
StringBuilder builder = new StringBuilder(s.length() + n);
for(int i = 0; i < n; i++){
builder.append(Character.toString(padding));
}
return builder.append(s).toString();
}
public static String pad(String s, int n, char padding){
StringBuilder pad = new StringBuilder(s.length() + n * 2);
StringBuilder value = new StringBuilder(n);
for(int i = 0; i < n; i++){
pad.append(padding);
}
return value.append(pad).append(s).append(pad).toString();
}
让我给一些情况下的答案,你需要给左/右填充(或前缀/后缀字符串或空格)在你连接到另一个字符串之前,你不想测试长度或任何if条件。
与所选答案相同,我更喜欢Apache Commons的StringUtils,但使用这种方式:
StringUtils.defaultString(StringUtils.leftPad(myString, 1))
解释:
myString:我输入的字符串,可以为空 stringutil的。leftPad(myString, 1):如果string为空,此语句也将返回null 然后使用defaultString给出空字符串,以防止连接null
@ck和@Marlon Tarak的答案是唯一使用char[]的答案,对于每秒有几个填充方法调用的应用程序来说,这是最好的方法。然而,它们没有利用任何数组操作优化,而且对我来说有点覆盖;这完全不需要循环。
public static String pad(String source, char fill, int length, boolean right){
if(source.length() > length) return source;
char[] out = new char[length];
if(right){
System.arraycopy(source.toCharArray(), 0, out, 0, source.length());
Arrays.fill(out, source.length(), length, fill);
}else{
int sourceOffset = length - source.length();
System.arraycopy(source.toCharArray(), 0, out, sourceOffset, source.length());
Arrays.fill(out, 0, sourceOffset, fill);
}
return new String(out);
}
简单测试方法:
public static void main(String... args){
System.out.println("012345678901234567890123456789");
System.out.println(pad("cats", ' ', 30, true));
System.out.println(pad("cats", ' ', 30, false));
System.out.println(pad("cats", ' ', 20, false));
System.out.println(pad("cats", '$', 30, true));
System.out.println(pad("too long for your own good, buddy", '#', 30, true));
}
输出:
012345678901234567890123456789
cats
cats
cats
cats$$$$$$$$$$$$$$$$$$$$$$$$$$
too long for your own good, buddy
Java联机程序,没有花哨的库。
// 6 characters padding example
String pad = "******";
// testcases for 0, 4, 8 characters
String input = "" | "abcd" | "abcdefgh"
左Pad,不要限制
result = pad.substring(Math.min(input.length(),pad.length())) + input;
results: "******" | "**abcd" | "abcdefgh"
右移,不要限制
result = input + pad.substring(Math.min(input.length(),pad.length()));
results: "******" | "abcd**" | "abcdefgh"
左衬垫,限制衬垫长度
result = (pad + input).substring(input.length(), input.length() + pad.length());
results: "******" | "**abcd" | "cdefgh"
右垫,限制垫的长度
result = (input + pad).substring(0, pad.length());
results: "******" | "abcd**" | "abcdef"
所有的字符串操作通常都需要非常高效——特别是当你处理大数据集的时候。我想要的东西是快速和灵活的,类似于你将在plsql pad命令。另外,我不想为一件小事包含一个巨大的库。考虑到这些因素,这些解决方案都不令人满意。这是我提出的解决方案,有最好的基准测试结果,如果有人可以改进它,请添加您的评论。
public static char[] lpad(char[] pStringChar, int pTotalLength, char pPad) {
if (pStringChar.length < pTotalLength) {
char[] retChar = new char[pTotalLength];
int padIdx = pTotalLength - pStringChar.length;
Arrays.fill(retChar, 0, padIdx, pPad);
System.arraycopy(pStringChar, 0, retChar, padIdx, pStringChar.length);
return retChar;
} else {
return pStringChar;
}
}
注意它是用String. tochararray()调用的,结果可以用new String((char[])result)转换为String。这样做的原因是,如果你应用多个操作,你可以在char[]上完成它们,而不需要在格式之间进行转换——在幕后,字符串存储为char[]。如果这些操作包含在String类本身中,那么效率将提高一倍——速度和内存方面。
在Dzone上找到的
用零填充:
String.format("|%020d|", 93); // prints: |00000000000000000093|
使用该函数。
private String leftPadding(String word, int length, char ch) {
return (length > word.length()) ? leftPadding(ch + word, length, ch) : word;
}
如何使用?
leftPadding(month, 2, '0');
输出: 01 02 03 04 ..11日12
从Java 11开始,string. repeat(int)可以用来左右填充给定的字符串。
System.out.println("*".repeat(5)+"apple");
System.out.println("apple"+"*".repeat(5));
输出:
*****apple
apple*****
另一种利用递归的解决方案。
这与所有JDK版本兼容,不需要外部库:
private static String addPadding(final String str, final int desiredLength, final String padBy) {
String result = str;
if (str.length() >= desiredLength) {
return result;
} else {
result += padBy;
return addPadding(result, desiredLength, padBy);
}
}
注意:这个解决方案将附加填充,与一个小调整,你可以前缀填充值。
这里有一个并行版本的你有很长的字符串:-)
int width = 100;
String s = "129018";
CharSequence padded = IntStream.range(0,width)
.parallel()
.map(i->i-(width-s.length()))
.map(i->i<0 ? '0' :s.charAt(i))
.collect(StringBuilder::new, (sb,c)-> sb.append((char)c), (sb1,sb2)->sb1.append(sb2));
这是一个高效的实用工具类,用于Java中的左填充,右填充,中心填充和零填充字符串。
package com.example;
/**
* Utility class for left pad, right pad, center pad and zero fill.
*/
public final class StringPadding {
public static String left(String string, int length, char fill) {
if (string.length() < length) {
char[] chars = string.toCharArray();
char[] output = new char[length];
int delta = length - chars.length;
for (int i = 0; i < length; i++) {
if (i < delta) {
output[i] = fill;
} else {
output[i] = chars[i - delta];
}
}
return new String(output);
}
return string;
}
public static String right(String string, int length, char fill) {
if (string.length() < length) {
char[] chars = string.toCharArray();
char[] output = new char[length];
for (int i = 0; i < length; i++) {
if (i < chars.length) {
output[i] = chars[i];
} else {
output[i] = fill;
}
}
return new String(output);
}
return string;
}
public static String center(String string, int length, char fill) {
if (string.length() < length) {
char[] chars = string.toCharArray();
int delta = length - chars.length;
int a = (delta % 2 == 0) ? delta / 2 : delta / 2 + 1;
int b = a + chars.length;
char[] output = new char[length];
for (int i = 0; i < length; i++) {
if (i < a) {
output[i] = fill;
} else if (i < b) {
output[i] = chars[i - a];
} else {
output[i] = fill;
}
}
return new String(output);
}
return string;
}
public static String zerofill(String string, int length) {
return left(string, length, '0');
}
private StringPadding() {
}
/**
* For tests!
*/
public static void main(String[] args) {
String string = "123";
char blank = ' ';
System.out.println("left pad: [" + StringPadding.left(string, 10, blank) + "]");
System.out.println("right pad: [" + StringPadding.right(string, 10, blank) + "]");
System.out.println("center pad: [" + StringPadding.center(string, 10, blank) + "]");
System.out.println("zero fill: [" + StringPadding.zerofill(string, 10) + "]");
}
}
输出如下:
left pad: [ 123]
right pad: [123 ]
center pad: [ 123 ]
zero fill: [0000000123]
概括一下Eko的答案(Java 11+):
public class StringUtils {
public static String padLeft(String s, char fill, int padSize) {
if (padSize < 0) {
var err = "padSize must be >= 0 (was " + padSize + ")";
throw new java.lang.IllegalArgumentException(err);
}
int repeats = Math.max(0, padSize - s.length());
return Character.toString(fill).repeat(repeats) + s;
}
public static String padRight(String s, char fill, int padSize) {
if (padSize < 0) {
var err = "padSize must be >= 0 (was " + padSize + ")";
throw new java.lang.IllegalArgumentException(err);
}
int repeats = Math.max(0, padSize - s.length());
return s + Character.toString(fill).repeat(repeats);
}
public static void main(String[] args) {
System.out.println(padLeft("", 'x', 5)); // => xxxxx
System.out.println(padLeft("1", 'x', 5)); // => xxxx1
System.out.println(padLeft("12", 'x', 5)); // => xxx12
System.out.println(padLeft("123", 'x', 5)); // => xx123
System.out.println(padLeft("1234", 'x', 5)); // => x1234
System.out.println(padLeft("12345", 'x', 5)); // => 12345
System.out.println(padLeft("123456", 'x', 5)); // => 123456
System.out.println(padRight("", 'x', 5)); // => xxxxx
System.out.println(padRight("1", 'x', 5)); // => 1xxxx
System.out.println(padRight("12", 'x', 5)); // => 12xxx
System.out.println(padRight("123", 'x', 5)); // => 123xx
System.out.println(padRight("1234", 'x', 5)); // => 1234x
System.out.println(padRight("12345", 'x', 5)); // => 12345
System.out.println(padRight("123456", 'x', 5)); // => 123456
System.out.println(padRight("1", 'x', -1)); // => throws
}
}
不管怎样,我一直在寻找一些可以填充的东西,然后我决定自己编写代码。它非常简洁,你可以很容易地从中推导出padLeft和padRight
/**
* Pads around a string, both left and right using pad as the template, aligning to the right or left as indicated.
* @param a the string to pad on both left and right
* @param pad the template to pad with, it can be of any size
* @param width the fixed width to output
* @param alignRight if true, when the input string is of odd length, adds an extra pad char to the left, so values are right aligned
* otherwise add an extra pad char to the right. When the input is of even length no extra chars will be inserted
* @return the input param a padded around.
*/
public static String padAround(String a, String pad, int width, boolean alignRight) {
if (pad.length() == 0)
throw new IllegalArgumentException("Pad cannot be an empty string!");
int delta = width - a.length();
if (delta < 1)
return a;
int half = delta / 2;
int remainder = delta % 2;
String padding = pad.repeat(((half+remainder)/pad.length()+1)); // repeating the padding to occupy all possible space
StringBuilder sb = new StringBuilder(width);
// sb.append( padding.substring(0,half + (alignRight ? 0 : remainder)));
sb.append(padding, 0, half + (alignRight ? 0 : remainder));
sb.append(a);
// sb.append( padding.substring(0,half + (alignRight ? remainder : 0)));
sb.append(padding, 0, half + (alignRight ? remainder : 0));
return sb.toString();
}
虽然它应该是相当快的,它可能会受益于使用一些韵母在这里和那里。
s =字符串填充 n =期望长度 c = Char到pad
private String padStart( String s, int n, char c ){
if( n <= 0 ) return s;
else return String.format("%" + n + "s", s).replace(' ', c);
}
为此编写自己的函数可能比其他答案更简单。
private static String padRight(String str, String padChar, int n) {
String paddedString = str;
while (paddedString.length() < n) {
paddedString = padChar + str;
}
return paddedString;
}
private static String padLeft(String str, String padChar, int n) {
String paddedString = str;
while (paddedString.length() < n) {
paddedString += padChar;
}
return paddedString;
}