我在javascript中创建了一个函数来生成一个具有一定长度的大写/小写或两者的随机字符串。
function randomString(max, option) {
var rNum = [];
if (option.toLowerCase() === "lowercase") {
for (let i = 0; i < max; i++) {
var randomNumber = Math.floor(Math.random() * (122 - 97) + 97);
rNum.push(randomNumber);
}
} else if (option.toLowerCase() === "uppercase") {
for (let i = 0; i < max; i++) {
var randomNumber = Math.floor(Math.random() * (90 - 65) + 65);
rNum.push(randomNumber);
}
} else if (option.toLowerCase() === "both") {
for (let i = 0; i < max; i++) {
var n = Math.floor(Math.random() * (122 - 65) + 65);
while ([91, 92, 93, 94, 95, 96].includes(n)) {
//If the random number is between 90 and 97 then we keep generating new numbers:
n = Math.floor(Math.random() * (122 - 65) + 65);
}
rNum.push(n);
}
} else {
return "Second parameter not valid, please type 'lowercase','uppercase' or 'both'";
}
var word = "";
for (let i = 0; i < rNum.length; i++) {
var letter = String.fromCharCode(rNum[i]);
word += letter;
}
return word;
}
现在我想创建第二个函数,它给定用户的任何字符串,它检查该单词是否出现在随机生成的字符串中。
我开始了它,说实话我根本不知道该怎么做。我如何检查那个长字符串中的哪个位置确实存在我不知道它有多长的单词。我想它可以看到它是否存在,但我如何找到它的位置呢?我尝试使用 array.indexOf(userString),但它只在第一次出现时返回。
function findWordsByChance(letters) {
var myString = randomString(999999, "both");
var splited = myString.split("");
if (splited.includes(letters)) {
console.log("this combination exists");
} else {
console.log("it doesnt");
}
for (let i = 1; i < splited.length - 1; i++) {
//check where it is (??)
}
}
findWordsByChance("Hi");
我对编程还很陌生,所以如果我犯了任何愚蠢的错误,请让我休息一下:) 顺便说一句,如果你们对如何以更有效的方式做我已经做过的事情有任何建议,我将不胜感激。
最佳答案
indexOf
接受定义起始偏移量的第二个参数,因此您可以使用它来循环并查找每个出现的位置。您只需将每次迭代的起点设置为紧接着最后一次出现的位置即可。这是我编写该函数的方式:
function indexOfAll(needle, haystack) {
var indices = [];
var index = 0;
while ((index = haystack.indexOf(needle, index)) > -1) {
indices.push(index);
index += needle.length;
}
return indices;
}
console.log(indexOfAll("oat", "goat in a boat"));
...但这对您来说可能更容易阅读:
function indexOfAll(needle, haystack) {
var indices = [];
var offset = 0;
while (haystack.indexOf(needle, offset) > -1) {
var indexOfThisOccurrence = haystack.indexOf(needle, offset);
indices.push(indexOfThisOccurrence);
offset = indexOfThisOccurrence + needle.length;
}
return indices;
}
console.log(indexOfAll("ug", "slug in a mug"));
关于javascript - 检查字母组合是否出现在随机单词序列中并确定它们的确切位置的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59814030/