为给定大小生成字符串

时间:2016-06-28 06:42:39

标签: java string random stringbuilder

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

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;
}

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

6 个答案:

答案 0 :(得分:4)

使用apache commons怎么样?它有一个RandomStringUtils类,它提供了你正在寻找的功能,但最后它也循环...

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)

答案 1 :(得分:1)

查看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

-SID

答案 2 :(得分:1)

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

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

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

答案 3 :(得分:0)

如果您只关心字符串长度,请执行导致较大值的数学运算。将该结果值转换为字符串并执行验证。如果你不想要数字,而不是将单个字符串'a'附加到stringBuilder。根据您追加到字符串构建器的字符串的长度,在您的for循环增量中附加一个大字符串。

答案 4 :(得分:0)

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

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

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

答案 5 :(得分:0)

请参考具有安全方式的link来创建任意指定长度的随机字符串。我在我的项目中使用它并且工作正常。

相关问题