我一直在解决代码战中的katas,我偶然发现了一个一般的代码问题,我似乎找不到答案。
这是我的代码:
function wave(str) {
let arr = [];
for (var i = 0; i < str.length; i++) {
str[i].match(/\S/) && arr.push(str.replace(str[i], str[i].toUpperCase()));
}
return arr;
};
(注意:输入始终为小写。)
在wave("abc def");
的情况下,代码完全可以实现我想要的功能:
["Abc def", "aBc def", "abC def", "abc Def", "abc dEf", "abc deF"]
=>函数采用一个字符串,以str[0]
开头的字符串中的一个字母大写,将新单词推入arr
,递增i
并重复该过程,直到i < str.length
,然后返回arr
和所有结果。
但是,例如,如果我输入wave("acc def");
,则只有字母c
的第一个出现才会大写:
["Acc def", "aCc def", "aCc def", "acc Def", "acc dEf", "acc deF"]
问题:为什么它会“跳过”第二个出现的“ c”字符,并且我如何定位字符串中第二个或第n个出现的字符?
答案 0 :(得分:1)
str.replace("x", "y")
将"x"
中第一个出现的str
替换为"y"
如果字符串中仅包含唯一字符,则您的方法有效,但是当"acc def"
您可以.slice()
将字符串分为三部分:
i
-> .slice(0, i)
的左侧部分i
-> str[i]
的字符i
-> .slice(i + 1)
后的其余部分根据需要修改str[i]
,然后将它们与.join("")
组合成一个字符串
function wave(str) {
const result = [];
for (let i = 0; i < str.length; i++) {
if (!str[i].match(/\S/)) continue;
result.push([
str.slice(0, i), /* the part left of str[i] */
str[i].toUpperCase(), /* str[i] */
str.slice(i + 1) /* the remaining part right of str[i] */
].join("")) // combine the parts in the array into a string
}
return result;
};
console.log(JSON.stringify(wave("abc def")));
console.log(JSON.stringify(wave("acc def")));
答案 1 :(得分:0)
当您说str.replace(str[i], str[i].toUpperCase())
时,您是在说:“用str[i]
替换str[i].toUpperCase()
的第一次出现”,这正是您的程序正在做的事情。
考虑像这样构建新字符串:
str.substring(0, i) + str[i].toUpperCase() + str.substring(i+1)