gpt4 book ai didi

javascript - 计算 Javascript 中所有字符串字符中某个字符在字符串中使用的次数

转载 作者:行者123 更新时间:2023-11-28 10:36:25 25 4
gpt4 key购买 nike

编写一个名为 strLetterCount 的函数,它接受一个字符串并返回一个新字符串,其中每个字符后跟该字符在字符串中出现的次数。

例如:

strLetterCount("taco"); // "t1a1c1o1"

我的代码在这里离目标很远,但这就是我得到的......

我将继续查找每个字母,然后尝试返回正确的字符串。我知道这不是一个好方法。有什么帮助吗?

function strLetterCount(str) {

var countA = 0;
var countB = 0;
var countC = 0;
var countD = 0;
var countE = 0;
var countF = 0;
var countG = 0;
var countH = 0;
var countI = 0;
var countJ = 0;
var countK = 0;
var countL = 0;
var countM = 0;
var countN = 0;
var countO = 0;
var countP = 0;
var countQ = 0;
var countR = 0;
var countS = 0;
var countT = 0;
var countU = 0;
var countV = 0;
var countW = 0;
var countX = 0;
var countY = 0;
var countZ = 0;

for (var i = 0; i < str.length; i++);
if (str[i] === 'a') {
countA++;
}
for (var i = 0; i < str.length; i++);
if (str[i] === 'b') {
countB++;
}
for (var i = 0; i < str.length; i++);
if (str[i] === 'c') {
countC++;
}
return {"a":countA,"b":countB,"c":countC}
}

console.log(
strLetterCount("The quick brown fox jumps over the lazy dog")
)

最佳答案

只需循环遍历字符串的每个字符,并将它们计入一个对象中。

一个简单的解决方案是:

let str = "The quick brown fox jumps over the lazy dog";

const count = string => {
const characters = {};
for (let character of string) {
characters[character] = characters[character] + 1 || 1;
}
return characters;
}

console.log(count(str));

您可以将结果用作:

let result = count(str);
console.log(result["o"]); // 4

更新

如果您需要字符串输出,一种选择是使用第二个循环来写出结果:

let str = "The quick brown fox jumps over the lazy dog";

const count = string => {
const characters = {};
let str = "";

for (let character of string) {
characters[character] = characters[character] + 1 || 1;
}
for (let key in characters) {
str += `${key}${characters[key]}`
}
return str;
}

console.log(count(str));

或者,如果您不关心格式:

return JSON.stringify(characters);

关于javascript - 计算 Javascript 中所有字符串字符中某个字符在字符串中使用的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60991235/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com