生成给定大小的字符串

Generate a String for a given size

如何生成给定大小的字符串?

int someLimit = GlobalLimits.BULK_SIZE;

我想要 3 个满足以下条件的字符串。

- RandomStr.length < someLimit.length

- RandomStr.length = someLimit.length

- RandomStr.length > someLimit.length

这是我目前尝试过的方法。

private String getLowerRandomString(int upto){
  StringBuilder sBuilder = new StringBuilder();
  for (int i = 0; i < upto; i++){
    sBuilder.append("A");
  }

  return sBuilder.toString();
}

我看到的问题是,如果我的限制 = 10000,它仍然循环到 9999,这是不必要的。如果您知道比这更好的方法,请分享。谢谢。


仅供参考: 我正在为一个简单的辅助方法编写单元测试。

public boolean isBulk(String text){
 int bulkLimit = ImportToolkit.getSizeLimit();
 if (text != null && text.length() > bulkLimit){
  return true;
 }
 return false;
}

所以,我想将不同大小的字符串作为参数传递给此方法,并想断言它是否会给我预期的结果。

如果你只关心字符串的长度,做一个结果很大的数学运算。将该结果值转换为字符串并执行验证。如果您不想要数字,则不要将单个字符串 'a' 附加到 stringBuilder。附加一个大字符串,并根据附加到字符串生成器的字符串的长度在 for 循环中递增。

使用 Random 生成小于 Limit 和大于 limit 的数字,并传递给函数以生成该长度的字符串

       lowerLimit= 0 + (int)(Math.random() * maximum); 
       higherLimit= minimum + (int)(Math.random() * maximum);
       smallerString= getLowerRandomString(lowerLimit);
       greaterString= getLowerRandomString(higherLimit);

有关限制随机数的帮助,请查看此 post。How do I generate random integers within a specific range in Java?

使用 apache commons 怎么样?它有一个 RandomStringUtils class 可以提供您正在寻找的功能,但最后它也会循环...

org.apache.commons.lang3.RandomStringUtils#randomAlphanumeric(int count)

来自 JavaDoc

Creates a random string whose length is the number of characters specified.

Characters will be chosen from the set of alpha-numeric characters.

Parameters:
    count - the length of random string to create
Returns:
    the random string

如果不需要随机,Stringutils 中还有另一种更便宜的方法:

org.apache.commons.lang3.StringUtils#repeat(char, int)

但最后也是循环...

来自 JavaDoc

Returns padding using the specified delimiter repeated to a given length.

 StringUtils.repeat('e', 0)  = ""
 StringUtils.repeat('e', 3)  = "eee"
 StringUtils.repeat('e', -2) = ""


Note: this method doesn't not support padding with Unicode Supplementary Characters as they require a pair of chars to be represented. If you are needing to support full I18N of your applications consider using repeat(String, int) instead.

Parameters:
    ch - character to repeat
    repeat - number of times to repeat char, negative treated as zero
Returns:
    String with repeated character
See Also:
    repeat(String, int)

看看 Xeger 库 here。你的代码会像这样。

    public static void main(String[] args){


 String regex="([0-9]{100})";     
    System.out.println(new Xeger(regex).generate());

}

输出:- 5262521775458685393102235626265923114201782357574146361524512101753254114567366125627554628148696482

您可以根据需要更改 100 或 1000。

Jar 位置 here

-席德

请参考 link,它具有为任意指定长度创建随机字符串的安全方法。我已经在我的项目中使用它并且效果很好。

如果你只关心字符串的长度,你可以这样做:

String str = new String(new char[SIZE]);

这很有用,例如,当您想要测试给定方法在给定特定长度的字符串时是否失败。