创建一个包含 n 个字符的字符串

发布于 2024-08-31 14:53:15 字数 298 浏览 13 评论 0 原文

Java中有没有办法创建一个具有指定数量指定字符的字符串?就我而言,我需要创建一个包含十个空格的字符串。我当前的代码是:

final StringBuffer outputBuffer = new StringBuffer(length);
for (int i = 0; i < length; i++){
   outputBuffer.append(" ");
}
return outputBuffer.toString();

有更好的方法来完成同样的事情吗?特别是,我想要一些快速的东西(就执行而言)。

Is there a way in Java to create a string with a specified number of a specified character? In my case, I would need to create a string with ten spaces. My current code is:

final StringBuffer outputBuffer = new StringBuffer(length);
for (int i = 0; i < length; i++){
   outputBuffer.append(" ");
}
return outputBuffer.toString();

Is there a better way to accomplish the same thing? In particular, I'd like something that is fast (in terms of execution).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(27

幻梦 2024-09-07 14:53:15

可能是使用 String API 的最短代码,仅:

String space10 = new String(new char[10]).replace('\0', ' ');

System.out.println("[" + space10 + "]");
// prints "[          ]"

作为一种方法,无需直接实例化 char

import java.nio.CharBuffer;

/**
 * Creates a string of spaces that is 'spaces' spaces long.
 *
 * @param spaces The number of spaces to add to the string.
 */
public String spaces( int spaces ) {
  return CharBuffer.allocate( spaces ).toString().replace( '\0', ' ' );
}

使用以下方式调用:

System.out.printf( "[%s]%n", spaces( 10 ) );

Likely the shortest code using the String API, exclusively:

String space10 = new String(new char[10]).replace('\0', ' ');

System.out.println("[" + space10 + "]");
// prints "[          ]"

As a method, without directly instantiating char:

import java.nio.CharBuffer;

/**
 * Creates a string of spaces that is 'spaces' spaces long.
 *
 * @param spaces The number of spaces to add to the string.
 */
public String spaces( int spaces ) {
  return CharBuffer.allocate( spaces ).toString().replace( '\0', ' ' );
}

Invoke using:

System.out.printf( "[%s]%n", spaces( 10 ) );
狼性发作 2024-09-07 14:53:15

我强烈建议不要手工编写循环。
在您的编程生涯中,您将一遍又一遍地这样做。
阅读你的代码的人(包括你)总是必须投入时间,即使只是几秒钟,来消化循环的含义。

相反,重用提供代码的可用库之一可以实现类似 Apache Commons Lang

StringUtils.repeat(' ', length);

这样你也不必担心性能,因此 StringBuilder、编译器优化等的所有细节都可以解决。隐。
如果该函数变得很慢,那么这将是库的一个错误。

使用 Java 11 变得更加容易:

" ".repeat(length);

I highly suggest not to write the loop by hand.
You will do that over and over again during the course of your programming career.
People reading your code - that includes you - always have to invest time, even if it are just some seconds, to digest the meaning of the loop.

Instead reuse one of the available libraries providing code that does just that like StringUtils.repeatfrom Apache Commons Lang:

StringUtils.repeat(' ', length);

That way you also do not have to bother about performance, thus all the gory details of StringBuilder, Compiler optimisations etc. are hidden.
If the function would turn out as slow it would be a bug of the library.

With Java 11 it becomes even easier:

" ".repeat(length);
飘过的浮云 2024-09-07 14:53:15

嗯,现在我想了一下,也许 Arrays.fill

char[] charArray = new char[length];
Arrays.fill(charArray, ' ');
String str = new String(charArray);

当然,我假设 fill 方法与您的代码执行相同的操作,因此它可能会执行大约一样的,但至少这样少了几行。

Hmm now that I think about it, maybe Arrays.fill:

char[] charArray = new char[length];
Arrays.fill(charArray, ' ');
String str = new String(charArray);

Of course, I assume that the fill method does the same thing as your code, so it will probably perform about the same, but at least this is fewer lines.

尤怨 2024-09-07 14:53:15

Java 11 起:

" ".repeat(10);

Java 8 起:

generate(() -> " ").limit(10).collect(joining());

其中:

import static java.util.stream.Collectors.joining;
import static java.util.stream.Stream.generate;

since Java 11:

" ".repeat(10);

since Java 8:

generate(() -> " ").limit(10).collect(joining());

where:

import static java.util.stream.Collectors.joining;
import static java.util.stream.Stream.generate;
如果没有 2024-09-07 14:53:15

for循环将被编译器优化。在像您这样的情况下,您不需要自己关心优化。相信编译器。

顺便说一句,如果有办法创建一个包含 n 个空格字符的字符串,那么它的编码方式与您刚才所做的相同。

The for loop will be optimized by the compiler. In such cases like yours you don't need to care about optimization on your own. Trust the compiler.

BTW, if there is a way to create a string with n space characters, than it's coded the same way like you just did.

小清晰的声音 2024-09-07 14:53:15

在 Java 8 中,您可以使用 String.join:

String.join("", Collections.nCopies(n, s));

In Java 8 you can use String.join:

String.join("", Collections.nCopies(n, s));
不一样的天空 2024-09-07 14:53:15

从 Java 11 开始,您可以简单地使用 String.repeat(count) 来解决您的问题。

返回一个字符串,其值是该字符串重复 count 次的串联。

如果此字符串为空或 count 为零,则返回空字符串。

因此,您的代码将如下所示,而不是循环:

" ".repeat(length);

Since Java 11 you can simply use String.repeat(count) to solve your problem.

Returns a string whose value is the concatenation of this string repeated count times.

If this string is empty or count is zero then the empty string is returned.

So instead of a loop your code would just look like this:

" ".repeat(length);
荒岛晴空 2024-09-07 14:53:15

如果你只想要空格,那么怎么样:

String spaces = (n==0)?"":String.format("%"+n+"s", "");

这将导致abs(n)空格;

If you want only spaces, then how about:

String spaces = (n==0)?"":String.format("%"+n+"s", "");

which will result in abs(n) spaces;

请帮我爱他 2024-09-07 14:53:15

我认为这是可能的更少的代码,它使用 Guava Joiner 类:

连接器.on("").join(Collections.nCopies(10, " "));

I think this is the less code it's possible, it uses Guava Joiner class:

Joiner.on("").join(Collections.nCopies(10, " "));

懵少女 2024-09-07 14:53:15

您可以使用标准String.format函数来生成N个空格。
例如:

String.format("%5c", ' ');

创建一个包含 5 个空格的字符串。

int count = 15;
String fifteenSpacebars = String.format("%" + count + "c", ' ');

生成一串 15 个空格键。

如果您希望另一个符号重复,则必须用所需的符号替换空格:

int count = 7;
char mySymbol = '#';
System.out.println(String.format("%" + count + "c", ' ').replaceAll("\\ ", "\\" + mySymbol));

输出:

#######

You can use standard String.format function for generate N spaces.
For example:

String.format("%5c", ' ');

Makes a string with 5 spaces.

or

int count = 15;
String fifteenSpacebars = String.format("%" + count + "c", ' ');

Makes a string of 15 spacebars.

If you want another symbol to repeat, you must replace spaces with your desired symbol:

int count = 7;
char mySymbol = '#';
System.out.println(String.format("%" + count + "c", ' ').replaceAll("\\ ", "\\" + mySymbol));

Output:

#######
万劫不复 2024-09-07 14:53:15

我的贡献基于快速求幂算法。

/**
 * Repeats the given {@link String} n times.
 * 
 * @param str
 *            the {@link String} to repeat.
 * @param n
 *            the repetition count.
 * @throws IllegalArgumentException
 *             when the given repetition count is smaller than zero.
 * @return the given {@link String} repeated n times.
 */
public static String repeat(String str, int n) {
    if (n < 0)
        throw new IllegalArgumentException(
                "the given repetition count is smaller than zero!");
    else if (n == 0)
        return "";
    else if (n == 1)
        return str;
    else if (n % 2 == 0) {
        String s = repeat(str, n / 2);
        return s.concat(s);
    } else
        return str.concat(repeat(str, n - 1));
}

我针对其他两种方法测试了该算法:

  • 使用 String.concat() 的常规 for 循环来连接字符串
  • 使用 StringBuilder 的常规 for 循环

测试代码(使用 for 循环和String.concat() 对于较大的 n 来说会变慢,所以我在第五次迭代后将其排除在外)。

/**
 * Test the string concatenation operation.
 * 
 * @param args
 */
public static void main(String[] args) {
    long startTime;
    String str = " ";

    int n = 1;
    for (int j = 0; j < 9; ++j) {
        n *= 10;
        System.out.format("Performing test with n=%d\n", n);

        startTime = System.currentTimeMillis();
        StringUtil.repeat(str, n);
        System.out
                .format("\tStringUtil.repeat() concatenation performed in    %d milliseconds\n",
                        System.currentTimeMillis() - startTime);

        if (j <5) {
            startTime = System.currentTimeMillis();
            String string = "";
            for (int i = 0; i < n; ++i)
                string = string.concat(str);
            System.out
                    .format("\tString.concat() concatenation performed in        %d milliseconds\n",
                            System.currentTimeMillis() - startTime);
        } else
            System.out
                    .format("\tString.concat() concatenation performed in        x milliseconds\n");
        startTime = System.currentTimeMillis();
        StringBuilder b = new StringBuilder();
        for (int i = 0; i < n; ++i)
            b.append(str);
        b.toString();
        System.out
                .format("\tStringBuilder.append() concatenation performed in %d milliseconds\n",
                        System.currentTimeMillis() - startTime);
    }
}

结果:

Performing test with n=10
    StringUtil.repeat() concatenation performed in    0 milliseconds
    String.concat() concatenation performed in        0 milliseconds
    StringBuilder.append() concatenation performed in 0 milliseconds
Performing test with n=100
    StringUtil.repeat() concatenation performed in    0 milliseconds
    String.concat() concatenation performed in        1 milliseconds
    StringBuilder.append() concatenation performed in 0 milliseconds
Performing test with n=1000
    StringUtil.repeat() concatenation performed in    0 milliseconds
    String.concat() concatenation performed in        1 milliseconds
    StringBuilder.append() concatenation performed in 1 milliseconds
Performing test with n=10000
    StringUtil.repeat() concatenation performed in    0 milliseconds
    String.concat() concatenation performed in        43 milliseconds
    StringBuilder.append() concatenation performed in 5 milliseconds
Performing test with n=100000
    StringUtil.repeat() concatenation performed in    0 milliseconds
    String.concat() concatenation performed in        1579 milliseconds
    StringBuilder.append() concatenation performed in 1 milliseconds
Performing test with n=1000000
    StringUtil.repeat() concatenation performed in    0 milliseconds
    String.concat() concatenation performed in        x milliseconds
    StringBuilder.append() concatenation performed in 10 milliseconds
Performing test with n=10000000
    StringUtil.repeat() concatenation performed in    7 milliseconds
    String.concat() concatenation performed in        x milliseconds
    StringBuilder.append() concatenation performed in 112 milliseconds
Performing test with n=100000000
    StringUtil.repeat() concatenation performed in    80 milliseconds
    String.concat() concatenation performed in        x milliseconds
    StringBuilder.append() concatenation performed in 1107 milliseconds
Performing test with n=1000000000
    StringUtil.repeat() concatenation performed in    1372 milliseconds
    String.concat() concatenation performed in        x milliseconds
    StringBuilder.append() concatenation performed in 12125 milliseconds

结论:

  • 对于较大的n - 使用递归方法
  • 对于较小的n - for循环具有足够的速度

My contribution based on the algorithm for fast exponentiation.

/**
 * Repeats the given {@link String} n times.
 * 
 * @param str
 *            the {@link String} to repeat.
 * @param n
 *            the repetition count.
 * @throws IllegalArgumentException
 *             when the given repetition count is smaller than zero.
 * @return the given {@link String} repeated n times.
 */
public static String repeat(String str, int n) {
    if (n < 0)
        throw new IllegalArgumentException(
                "the given repetition count is smaller than zero!");
    else if (n == 0)
        return "";
    else if (n == 1)
        return str;
    else if (n % 2 == 0) {
        String s = repeat(str, n / 2);
        return s.concat(s);
    } else
        return str.concat(repeat(str, n - 1));
}

I tested the algorithm against two other approaches:

  • Regular for loop using String.concat() to concatenate string
  • Regular for loop using a StringBuilder

Test code (concatenation using a for loop and String.concat() becomes to slow for large n, so I left it out after the 5th iteration).

/**
 * Test the string concatenation operation.
 * 
 * @param args
 */
public static void main(String[] args) {
    long startTime;
    String str = " ";

    int n = 1;
    for (int j = 0; j < 9; ++j) {
        n *= 10;
        System.out.format("Performing test with n=%d\n", n);

        startTime = System.currentTimeMillis();
        StringUtil.repeat(str, n);
        System.out
                .format("\tStringUtil.repeat() concatenation performed in    %d milliseconds\n",
                        System.currentTimeMillis() - startTime);

        if (j <5) {
            startTime = System.currentTimeMillis();
            String string = "";
            for (int i = 0; i < n; ++i)
                string = string.concat(str);
            System.out
                    .format("\tString.concat() concatenation performed in        %d milliseconds\n",
                            System.currentTimeMillis() - startTime);
        } else
            System.out
                    .format("\tString.concat() concatenation performed in        x milliseconds\n");
        startTime = System.currentTimeMillis();
        StringBuilder b = new StringBuilder();
        for (int i = 0; i < n; ++i)
            b.append(str);
        b.toString();
        System.out
                .format("\tStringBuilder.append() concatenation performed in %d milliseconds\n",
                        System.currentTimeMillis() - startTime);
    }
}

Results:

Performing test with n=10
    StringUtil.repeat() concatenation performed in    0 milliseconds
    String.concat() concatenation performed in        0 milliseconds
    StringBuilder.append() concatenation performed in 0 milliseconds
Performing test with n=100
    StringUtil.repeat() concatenation performed in    0 milliseconds
    String.concat() concatenation performed in        1 milliseconds
    StringBuilder.append() concatenation performed in 0 milliseconds
Performing test with n=1000
    StringUtil.repeat() concatenation performed in    0 milliseconds
    String.concat() concatenation performed in        1 milliseconds
    StringBuilder.append() concatenation performed in 1 milliseconds
Performing test with n=10000
    StringUtil.repeat() concatenation performed in    0 milliseconds
    String.concat() concatenation performed in        43 milliseconds
    StringBuilder.append() concatenation performed in 5 milliseconds
Performing test with n=100000
    StringUtil.repeat() concatenation performed in    0 milliseconds
    String.concat() concatenation performed in        1579 milliseconds
    StringBuilder.append() concatenation performed in 1 milliseconds
Performing test with n=1000000
    StringUtil.repeat() concatenation performed in    0 milliseconds
    String.concat() concatenation performed in        x milliseconds
    StringBuilder.append() concatenation performed in 10 milliseconds
Performing test with n=10000000
    StringUtil.repeat() concatenation performed in    7 milliseconds
    String.concat() concatenation performed in        x milliseconds
    StringBuilder.append() concatenation performed in 112 milliseconds
Performing test with n=100000000
    StringUtil.repeat() concatenation performed in    80 milliseconds
    String.concat() concatenation performed in        x milliseconds
    StringBuilder.append() concatenation performed in 1107 milliseconds
Performing test with n=1000000000
    StringUtil.repeat() concatenation performed in    1372 milliseconds
    String.concat() concatenation performed in        x milliseconds
    StringBuilder.append() concatenation performed in 12125 milliseconds

Conclusion:

  • For large n - use the recursive approach
  • For small n - for loop has sufficient speed
往事随风而去 2024-09-07 14:53:15

这个怎么样?

char[] bytes = new char[length];
Arrays.fill(bytes, ' ');
String str = new String(bytes);

How about this?

char[] bytes = new char[length];
Arrays.fill(bytes, ' ');
String str = new String(bytes);
电影里的梦 2024-09-07 14:53:15

考虑到我们有:

String c = "c"; // character to repeat, for empty it would be " ";
int n = 4; // number of times to repeat
String EMPTY_STRING = ""; // empty string (can be put in utility class)

Java 8(使用 Stream)

String resultOne = IntStream.range(0,n)
   .mapToObj(i->c).collect(Collectors.joining(EMPTY_STRING)); // cccc

Java 8(使用 nCopies)

String resultTwo = String.join(EMPTY_STRING, Collections.nCopies(n, c)); //cccc

Considering we have:

String c = "c"; // character to repeat, for empty it would be " ";
int n = 4; // number of times to repeat
String EMPTY_STRING = ""; // empty string (can be put in utility class)

Java 8 (Using Stream)

String resultOne = IntStream.range(0,n)
   .mapToObj(i->c).collect(Collectors.joining(EMPTY_STRING)); // cccc

Java 8 (Using nCopies)

String resultTwo = String.join(EMPTY_STRING, Collections.nCopies(n, c)); //cccc
浊酒尽余欢 2024-09-07 14:53:15

使用 StringUtils:
StringUtils.repeat(' ', 10)

Use StringUtils:
StringUtils.repeat(' ', 10)

泡沫很甜 2024-09-07 14:53:15

Guava 的最短解决方案:

Strings.repeat(" ", len)

通过 在 java 中重复字符串的简单方法< /a>.

The shortest solution with Guava:

Strings.repeat(" ", len)

Via Simple way to repeat a String in java.

深白境迁sunset 2024-09-07 14:53:15

这对我来说是有效的,无需在 Java 8 中使用任何外部库,

String sampleText = "test"
int n = 3;
String output = String.join("", Collections.nCopies(n, sampleText));
System.out.println(output);

输出是

testtesttest

This worked out for me without using any external libraries in Java 8

String sampleText = "test"
int n = 3;
String output = String.join("", Collections.nCopies(n, sampleText));
System.out.println(output);

And the output is

testtesttest
无人问我粥可暖 2024-09-07 14:53:15

RandomStringUtils可以根据给定的输入大小创建字符串。
无法评论速度,但它是单班轮。

RandomStringUtils.random(5,"\t");

创建一个输出

\t\t\t\t\t

如果您不想在代码中看到 \0,则

RandomStringUtils has a provision to create a string from given input size.
Cant comment on the speed, but its a one liner.

RandomStringUtils.random(5,"\t");

creates an output

\t\t\t\t\t

preferable if you dont want to see \0 in your code.

笨笨の傻瓜 2024-09-07 14:53:15

整数 c = 10;
字符串空格 = String.format("%" +c+ "c", ' ');
这将解决你的问题。

int c = 10;
String spaces = String.format("%" +c+ "c", ' ');
this will solve your problem.

以往的大感动 2024-09-07 14:53:15

在大多数情况下,您只需要达到一定长度的字符串,例如 100 个空格。您可以准备一个字符串数组,其中索引号等于填充空格的字符串的大小,并查找该字符串(如果所需的长度在限制内),或者根据需要创建它(如果它在边界之外)。

In most cases you only need Strings upto a certains length, say 100 spaces. You could prepare an array of Strings where the index number is equal to the size of the space-filled string and lookup the string, if the required length is within the limits or create it on demand if it's outside the boundary.

苏大泽ㄣ 2024-09-07 14:53:15

为了获得良好的性能,请结合 aznilamirFrusteratedWithFormsDesigner

private static final String BLANKS = "                       ";
private static String getBlankLine( int length )
{
    if( length <= BLANKS.length() )
    {
        return BLANKS.substring( 0, length );
    }
    else
    {
        char[] array = new char[ length ];
        Arrays.fill( array, ' ' );
        return new String( array );
    }
}

根据您的要求调整 BLANKS 的大小。我的特定 BLANKS 字符串长度约为 200 个字符。

For good performance, combine answers from aznilamir and from FrustratedWithFormsDesigner

private static final String BLANKS = "                       ";
private static String getBlankLine( int length )
{
    if( length <= BLANKS.length() )
    {
        return BLANKS.substring( 0, length );
    }
    else
    {
        char[] array = new char[ length ];
        Arrays.fill( array, ' ' );
        return new String( array );
    }
}

Adjust size of BLANKS depending on your requirements. My specific BLANKS string is about 200 characters length.

亚希 2024-09-07 14:53:15

只需将 StringBuffer 替换为 StringBuilder。很难打败它。

如果你的长度很大,你可能会实现一些更有效的
(但更笨拙)自追加,在每次迭代中复制长度:

 public static String dummyString(char c, int len) {
  if( len < 1 ) return "";
  StringBuilder sb = new StringBuilder(len).append(c);
  int remnant = len - sb.length();
  while(remnant  > 0) {
   if( remnant  >= sb.length() ) sb.append(sb);
   else sb.append(sb.subSequence(0, remnant));
   remnant  = len - sb.length();
  }
  return sb.toString();
 }

另外,您可以尝试 Arrays.fill() 方法(FrusteratedWithFormsDesigner 的答案)。

Just replace your StringBuffer with a StringBuilder. Hard to beat that.

If your length is a big number, you might implement some more efficient
(but more clumsy) self-appendding, duplicating the length in each iteration:

 public static String dummyString(char c, int len) {
  if( len < 1 ) return "";
  StringBuilder sb = new StringBuilder(len).append(c);
  int remnant = len - sb.length();
  while(remnant  > 0) {
   if( remnant  >= sb.length() ) sb.append(sb);
   else sb.append(sb.subSequence(0, remnant));
   remnant  = len - sb.length();
  }
  return sb.toString();
 }

Also, you might try the Arrays.fill() aproach (FrustratedWithFormsDesigner's answer).

陌若浮生 2024-09-07 14:53:15

您可以将 StringBuffer 替换为 StringBuilder (后者不同步,在单线程应用程序中可能更快)

并且您可以创建 StringBuilder实例一次,而不是每次需要时创建它。

像这样的事情:

class BuildString {
     private final StringBuilder builder = new StringBuilder();
     public String stringOf( char c , int times ) {

         for( int i = 0 ; i < times ; i++  ) {
             builder.append( c );
         }
         String result = builder.toString();
         builder.delete( 0 , builder.length() -1 );
         return result;
      }

  }

并像这样使用它:

 BuildString createA = new BuildString();
 String empty = createA.stringOf( ' ', 10 );

如果将 createA 作为实例变量,则可以节省创建实例的时间。

这不是线程安全的,如果你有多个线程,每个线程应该有自己的副本。

You can replace StringBuffer with StringBuilder ( the latter is not synchronized, may be a faster in a single thread app )

And you can create the StringBuilder instance once, instead of creating it each time you need it.

Something like this:

class BuildString {
     private final StringBuilder builder = new StringBuilder();
     public String stringOf( char c , int times ) {

         for( int i = 0 ; i < times ; i++  ) {
             builder.append( c );
         }
         String result = builder.toString();
         builder.delete( 0 , builder.length() -1 );
         return result;
      }

  }

And use it like this:

 BuildString createA = new BuildString();
 String empty = createA.stringOf( ' ', 10 );

If you hold your createA as a instance variable, you may save time creating instances.

This is not thread safe, if you have multi threads, each thread should have its own copy.

沉鱼一梦 2024-09-07 14:53:15

有一个这样的方法。这会在给定 String 末尾附加所需的空格,以使给定 String 的长度达到特定长度。

public static String fillSpaces (String str) {

    // the spaces string should contain spaces exceeding the max needed
    String spaces = "                                                   ";
    return str + spaces.substring(str.length());
}

Have a method like this. This appends required spaces at the end of the given String to make a given String to length of specific length.

public static String fillSpaces (String str) {

    // the spaces string should contain spaces exceeding the max needed
    String spaces = "                                                   ";
    return str + spaces.substring(str.length());
}
梦里的微风 2024-09-07 14:53:15

希望字符串具有固定大小,因此您可以填充或截断,以将数据制成表格...

class Playground {
    private static String fixStrSize(String s, int n) {
        return String.format("%-" + n + "s", String.format("%." + n +"s", s));
    }

    public static void main(String[ ] args) {
        System.out.println("|"+fixStrSize("Hell",8)+"|");
        System.out.println("|"+fixStrSize("Hells Bells Java Smells",8)+"|");
    }
}

|Hell    |
|Hells Be|

优秀参考 这里

Want String to be of fixed size, so you either pad or truncate, for tabulating data...

class Playground {
    private static String fixStrSize(String s, int n) {
        return String.format("%-" + n + "s", String.format("%." + n +"s", s));
    }

    public static void main(String[ ] args) {
        System.out.println("|"+fixStrSize("Hell",8)+"|");
        System.out.println("|"+fixStrSize("Hells Bells Java Smells",8)+"|");
    }
}

|Hell    |
|Hells Be|

Excellent reference here.

简单爱 2024-09-07 14:53:15

也可以使用如下简单方法

public static String padString(String str, int leng,char chr) {
        for (int i = str.length(); i <= leng; i++)
            str += chr;
        return str;
    }

A simple method like below can also be used

public static String padString(String str, int leng,char chr) {
        for (int i = str.length(); i <= leng; i++)
            str += chr;
        return str;
    }
痞味浪人 2024-09-07 14:53:15

这个怎么样?

public String fillSpaces(int len) {
    /* the spaces string should contain spaces exceeding the max needed */  
    String spaces = "                                                   ";
    return spaces.substring(0,len);
}

编辑:我编写了一个简单的代码来测试这个概念,这里是我发现的。

方法 1:在循环中添加单个空格:

  public String execLoopSingleSpace(int len){
    StringBuilder sb = new StringBuilder();

    for(int i=0; i < len; i++) {
        sb.append(' ');
    }

    return sb.toString();
  }

方法 2:追加 100 个空格并循环,然后子字符串:

  public String execLoopHundredSpaces(int len){
    StringBuilder sb = new StringBuilder("          ")
            .append("          ").append("          ").append("          ")
            .append("          ").append("          ").append("          ")
            .append("          ").append("          ").append("          ");

    for (int i=0; i < len/100 ; i++) {
        sb.append("          ")
            .append("          ").append("          ").append("          ")
            .append("          ").append("          ").append("          ")
            .append("          ").append("          ").append("          ");
    }

    return sb.toString().substring(0,len);
  }

我得到的结果创建了 12,345,678 个空格:

C:\docs\Projects> java FillSpace 12345678
method 1: append single spaces for 12345678 times. Time taken is **234ms**. Length of String is 12345678
method 2: append 100 spaces for 123456 times. Time taken is **141ms**. Length of String is 12345678
Process java exited with code 0

对于 10,000,000 个空格:

C:\docs\Projects> java FillSpace 10000000
method 1: append single spaces for 10000000 times. Time taken is **157ms**. Length of String is 10000000
method 2: append 100 spaces for 100000 times. Time taken is **109ms**. Length of String is 10000000
Process java exited with code 0

将直接分配和迭代相结合总是需要更少的时间,平均少 60 毫秒创造巨大的空间。对于较小的尺寸,这两个结果都可以忽略不计。

但请继续发表评论:-)

how about this?

public String fillSpaces(int len) {
    /* the spaces string should contain spaces exceeding the max needed */  
    String spaces = "                                                   ";
    return spaces.substring(0,len);
}

EDIT: I've written a simple code to test the concept and here what i found.

Method 1: adding single space in a loop:

  public String execLoopSingleSpace(int len){
    StringBuilder sb = new StringBuilder();

    for(int i=0; i < len; i++) {
        sb.append(' ');
    }

    return sb.toString();
  }

Method 2: append 100 spaces and loop, then substring:

  public String execLoopHundredSpaces(int len){
    StringBuilder sb = new StringBuilder("          ")
            .append("          ").append("          ").append("          ")
            .append("          ").append("          ").append("          ")
            .append("          ").append("          ").append("          ");

    for (int i=0; i < len/100 ; i++) {
        sb.append("          ")
            .append("          ").append("          ").append("          ")
            .append("          ").append("          ").append("          ")
            .append("          ").append("          ").append("          ");
    }

    return sb.toString().substring(0,len);
  }

The result I get creating 12,345,678 spaces:

C:\docs\Projects> java FillSpace 12345678
method 1: append single spaces for 12345678 times. Time taken is **234ms**. Length of String is 12345678
method 2: append 100 spaces for 123456 times. Time taken is **141ms**. Length of String is 12345678
Process java exited with code 0

and for 10,000,000 spaces:

C:\docs\Projects> java FillSpace 10000000
method 1: append single spaces for 10000000 times. Time taken is **157ms**. Length of String is 10000000
method 2: append 100 spaces for 100000 times. Time taken is **109ms**. Length of String is 10000000
Process java exited with code 0

combining direct allocation and iteration always takes less time, on average 60ms less when creating huge spaces. For smaller sizes, both results are negligible.

But please continue to comment :-)

烦人精 2024-09-07 14:53:15

我知道没有内置方法可以满足您的要求。但是,对于像 10 这样的小固定长度,您的方法应该足够快。

I know of no built-in method for what you're asking about. However, for a small fixed length like 10, your method should be plenty fast.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文