gpt4 book ai didi

java - 生成给定大小的字符串

转载 作者:搜寻专家 更新时间:2023-11-01 02:04:26 24 4
gpt4 key购买 nike

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

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

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

最佳答案

使用 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)

关于java - 生成给定大小的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38068838/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com