简体   繁体   English

将 String 变量拆分为指定长度的随机子字符串

[英]Split a String variable into a random substring with a specified length

In java.在爪哇。 It should use the random number generator to return a randomly chosen substring of text that has the specified length.它应该使用随机数生成器来返回一个随机选择的具有指定长度的文本子字符串。 If the length is either negative or greater than the length of text, the method should throw an IllegalArgumentException.如果长度为负数或大于文本长度,则该方法应抛出 IllegalArgumentException。 For example, chooseSubstring("abcde", 4, new Random()) should return "abcd" about half the time and "bcde" about half the time.例如,chooseSubstring("abcde", 4, new Random()) 大约一半的时间应该返回“abcd”,大约一半的时间返回“bcde”。

public static String chooseSubstring (String text, int length, Random rand)
{
    int randomNum = rand.nextInt(length);
    String answer = text.substring(randomNum);
    return answer;
}

Basically, I want to return a substring from the variable text .基本上,我想从变量text返回一个子字符串。 The substring must be the length of the variable length.子串必须是可变长度的长度。 The beginning of this substring should start at a random location determined by a random number generator.此子字符串的开头应从随机数生成器确定的随机位置开始。 My problem is that the random number generator is not making sure the substring is the correct length.我的问题是随机数生成器没有确保子字符串的长度正确。

        System.out.println(chooseSubstring("abcde", 4, new Random()));

Should return abcd and bcde about the same amount of times.应该返回abcdbcde大约相同的次数。 Instead it is returning: bcde cde de abcde .相反,它正在返回: bcde cde de abcde Any info about how to solve this would greatly help thanks!任何有关如何解决此问题的信息都会非常有帮助,谢谢!

Your code is taking a substring at a random index between 0 and length , exclusive.您的代码在 0 和length之间的随机索引处获取子字符串,不包括在内。 You have to specify the end index so it doesn't extend to the end of the string.您必须指定结束索引,以便它不会扩展到字符串的末尾。 You also need to reduce the range of the starting index so the end index doesn't go past the string:您还需要减少起始索引的范围,以便结束索引不会超过字符串:

int randomNum = rand.nextInt(text.length() - length + 1);
String answer = text.substring(randomNum, randomNum + length);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM