替换字符串中的随机字符
Replace random characters in string
我正在尝试用一定数量的字符替换随机字符串字符
一个特定的字符(即:"*"
),我将在下面的代码中解释更多。
/**
* Returns a string with replaced amount of strings with a set string
* @param {string} str The input
* @param {number} amountToReplace The amount of letters you want to replace
* @param {string} generalReplace The general letter to replace with
* @returns {string} Returns a string with the string thats finished
*/
var str = 'thisisastring';
var amountToReplace = 5;
var generalReplace = '*'
// Function over here, e.g. with the name replacer
var returnMe = replacer(str, amountToReplac
抱歉,如果这些参数听起来很混乱,我对它们还是陌生的!!
所以字符串,str
是输入的字符串,amountToReplace
是要替换的字母数量,generalReplace
是要替换的通用字符.
如果金额为 5
,我期望的输出类似于:
原文: thisisastring
输出: th*s**as*ri*g
返回的字符串应该替换字符串中的随机部分(但仍然执行输入的数量,而不是执行 5 个替换但返回 3 个作为常见匹配项)。
谢谢!
最小的(可以说是最简单的):
- 将字符串拆分成数组
[...str] // (is now an Array)
- 在随机点循环插入一个带有替换字符的数组,例如:
["t", "h", "i", ["*"], "i", ["*"], ...
continue
循环直到 i
(amount
)不是 0
并且直到迭代索引处的当前值是数组。
- 一旦完成,因为我们有一个二维数组,使用
Array.prototype.flat()
使其成为一维的,例如:["t", "h", "i", "*", "i", "*", ...
- 并使用
Array.prototype.join()
将其转换回字符串
const replacer = (str, i, rep) => {
if (!str) return; // Do nothing if no string passed
const arr = [...str]; // Convert String to Array
const len = arr.length
i = Math.min(Math.abs(i), len); // Fix to Positive and not > len
while (i) {
const r = ~~(Math.random() * len);
if (Array.isArray(arr[r])) continue; // Skip if is array (not a character)
arr[r] = [rep]; // Insert an Array with the rep char
--i;
}
return arr.flat().join("");
};
console.log(replacer("thisisastring", 5, "*"));
上面的例子是久经考验的并且即使在以下情况下也能正常工作:
- 没有字符串或为空
- 该字符串已包含所有星号
"*****"
amount
大于字符串长度
amount
为负整数
最长的:
- 生成 N (
amountToReplace
) 个随机唯一整数数组
- 将输入字符串转换为数组,迭代它,将随机索引中的每个字符替换为
generalReplace
“*”字符
/**
* Create an array of unique integers
* @param {Integer} len Array length
* @param {Integer} max Max integer value
* @returns {Array} Array of random Unique integers
*/
function genArrRandInt(len, max) {
const nums = new Set();
while (nums.size !== len) nums.add(Math.floor(Math.random() * max));
return [...nums];
};
/**
* Returns a string with replaced amount of strings with a set string
* @param {string} str The input
* @param {number} amountToReplace The amount of letters you want to replace
* @param {string} generalReplace The general letter to replace with
* @returns {string} Returns a string with the string thats finished
*/
function replacer(str, amountToReplace, generalReplace) {
const strArr = [...str];
const uniqueArr = genArrRandInt(amountToReplace, str.length);
uniqueArr.forEach(i => strArr[i] = generalReplace);
return strArr.join("");
}
const str = "thisisastring";
const amountToReplace = 5;
const generalReplace = "*";
// Function over here, e.g. with the name replacer
const returnMe = replacer(str, amountToReplace, generalReplace);
console.log(returnMe);
function replacer(string, amount) {
// If string contains all '*' return string
if ([...string.matchAll(/\*/g)].length === string.length) {
return string
}
// copy the ori string convert to array
let res = [...string]
let i = amount
let e = ['*', ' ']
// iterate amount times
while (i >= 1) {
// get random index in array
const randomIdx = Math.floor(Math.random() * string.length)
// get char at index
const randomChar = res[randomIdx]
// check if it not '*' or ' '
if (!e.includes(randomChar)) {
// replace char with '*'
res.splice(randomIdx, 1, '*')
i--
}
}
return res.join('')
}
你可以试试这个。
代码可能类似于:
function rand(min, max){
let mn = min, mx = max;
if(mx === undefined){
mx = mn; mn = 0;
}
return mn+Math.floor(Math.random()*(mx-mn+1));
}
function randCharReplace(string, replaceWith = '*', replaceCount = 1){
const a = string.split(''), m = a.length-1;
const f = ()=>{
return rand(0, m);
}
for(let i=0,r; i<replaceCount; i++){
while(r === undefined || a[r] === replaceWith){
r = f();
}
a[r] = replaceWith;
}
return a.join('');
}
console.log(randCharReplace('thisisastring', '*', 5));
使用 Set
的更高效方法
function replacer(str, len = 0, generalReplacer) {
const length = len > str.length ? str.length : len,
set = new Set(),
newStr = [];
while (set.size !== length) {
set.add(Math.floor(Math.random() * str.length));
}
for (let i = 0; i < str.length; ++i) {
set.has(i) ? newStr.push(generalReplacer) : newStr.push(str[i]);
}
return newStr.join("");
}
console.log(replacer("thisisastring", 5, "*"));
console.log(replacer("thisisastring", 1, "*"));
console.log(replacer("thisisastring", 7, "*"));
我正在尝试用一定数量的字符替换随机字符串字符
一个特定的字符(即:"*"
),我将在下面的代码中解释更多。
/**
* Returns a string with replaced amount of strings with a set string
* @param {string} str The input
* @param {number} amountToReplace The amount of letters you want to replace
* @param {string} generalReplace The general letter to replace with
* @returns {string} Returns a string with the string thats finished
*/
var str = 'thisisastring';
var amountToReplace = 5;
var generalReplace = '*'
// Function over here, e.g. with the name replacer
var returnMe = replacer(str, amountToReplac
抱歉,如果这些参数听起来很混乱,我对它们还是陌生的!!
所以字符串,str
是输入的字符串,amountToReplace
是要替换的字母数量,generalReplace
是要替换的通用字符.
如果金额为 5
,我期望的输出类似于:
原文: thisisastring
输出: th*s**as*ri*g
返回的字符串应该替换字符串中的随机部分(但仍然执行输入的数量,而不是执行 5 个替换但返回 3 个作为常见匹配项)。
谢谢!
最小的(可以说是最简单的):
- 将字符串拆分成数组
[...str] // (is now an Array)
- 在随机点循环插入一个带有替换字符的数组,例如:
["t", "h", "i", ["*"], "i", ["*"], ...
continue
循环直到i
(amount
)不是0
并且直到迭代索引处的当前值是数组。- 一旦完成,因为我们有一个二维数组,使用
Array.prototype.flat()
使其成为一维的,例如:["t", "h", "i", "*", "i", "*", ...
- 并使用
Array.prototype.join()
将其转换回字符串
const replacer = (str, i, rep) => {
if (!str) return; // Do nothing if no string passed
const arr = [...str]; // Convert String to Array
const len = arr.length
i = Math.min(Math.abs(i), len); // Fix to Positive and not > len
while (i) {
const r = ~~(Math.random() * len);
if (Array.isArray(arr[r])) continue; // Skip if is array (not a character)
arr[r] = [rep]; // Insert an Array with the rep char
--i;
}
return arr.flat().join("");
};
console.log(replacer("thisisastring", 5, "*"));
上面的例子是久经考验的并且即使在以下情况下也能正常工作:
- 没有字符串或为空
- 该字符串已包含所有星号
"*****"
amount
大于字符串长度amount
为负整数
最长的:
- 生成 N (
amountToReplace
) 个随机唯一整数数组 - 将输入字符串转换为数组,迭代它,将随机索引中的每个字符替换为
generalReplace
“*”字符
/**
* Create an array of unique integers
* @param {Integer} len Array length
* @param {Integer} max Max integer value
* @returns {Array} Array of random Unique integers
*/
function genArrRandInt(len, max) {
const nums = new Set();
while (nums.size !== len) nums.add(Math.floor(Math.random() * max));
return [...nums];
};
/**
* Returns a string with replaced amount of strings with a set string
* @param {string} str The input
* @param {number} amountToReplace The amount of letters you want to replace
* @param {string} generalReplace The general letter to replace with
* @returns {string} Returns a string with the string thats finished
*/
function replacer(str, amountToReplace, generalReplace) {
const strArr = [...str];
const uniqueArr = genArrRandInt(amountToReplace, str.length);
uniqueArr.forEach(i => strArr[i] = generalReplace);
return strArr.join("");
}
const str = "thisisastring";
const amountToReplace = 5;
const generalReplace = "*";
// Function over here, e.g. with the name replacer
const returnMe = replacer(str, amountToReplace, generalReplace);
console.log(returnMe);
function replacer(string, amount) {
// If string contains all '*' return string
if ([...string.matchAll(/\*/g)].length === string.length) {
return string
}
// copy the ori string convert to array
let res = [...string]
let i = amount
let e = ['*', ' ']
// iterate amount times
while (i >= 1) {
// get random index in array
const randomIdx = Math.floor(Math.random() * string.length)
// get char at index
const randomChar = res[randomIdx]
// check if it not '*' or ' '
if (!e.includes(randomChar)) {
// replace char with '*'
res.splice(randomIdx, 1, '*')
i--
}
}
return res.join('')
}
你可以试试这个。
代码可能类似于:
function rand(min, max){
let mn = min, mx = max;
if(mx === undefined){
mx = mn; mn = 0;
}
return mn+Math.floor(Math.random()*(mx-mn+1));
}
function randCharReplace(string, replaceWith = '*', replaceCount = 1){
const a = string.split(''), m = a.length-1;
const f = ()=>{
return rand(0, m);
}
for(let i=0,r; i<replaceCount; i++){
while(r === undefined || a[r] === replaceWith){
r = f();
}
a[r] = replaceWith;
}
return a.join('');
}
console.log(randCharReplace('thisisastring', '*', 5));
使用 Set
的更高效方法function replacer(str, len = 0, generalReplacer) {
const length = len > str.length ? str.length : len,
set = new Set(),
newStr = [];
while (set.size !== length) {
set.add(Math.floor(Math.random() * str.length));
}
for (let i = 0; i < str.length; ++i) {
set.has(i) ? newStr.push(generalReplacer) : newStr.push(str[i]);
}
return newStr.join("");
}
console.log(replacer("thisisastring", 5, "*"));
console.log(replacer("thisisastring", 1, "*"));
console.log(replacer("thisisastring", 7, "*"));