I’m trying to solve a coding problem and it seems my thinking process is wrong in this problem. I’m trying to solve the following:
/*
Given a string and a number n, replace every nth character with '_'.
"foreigner", 2 => "f_r_i_n_r"
"leetcode", 3 => "le_tc_de"
"leetcode", 1 => "________"
*/
function replaceChar(string1, number) {
let stringArr = string1.split("")
for (let i = 0; i < stringArr.length; i++) {
if (i === i + 1) {
stringArr[i] = "_"
}
}
stringArr.join('')
console.log(stringArr)
}
replaceChar("foreigner", 2);
The function at bottom is written by me and it seems it’s not working as I intended.
>Solution :
You got the funcion almost right, except for the if (i === i + 1) condition…
You need to check if the remainder of (i + 1 / number) is 0:
function replaceChar(string1, number) {
let stringArr = string1.split("")
for (let i = 0; i < stringArr.length; i++) {
if ((i + 1) % number === 0) {
stringArr[i] = "_"
}
}
console.log(stringArr)
// or: return stringArr.join('')?
}
replaceChar("foreigner", 2);
BTW As other pointed out, the stringArr.join('') is not doing anything – you probably need to assign it to a variable and return it (or return it directly – as proposed in the code).