我需要计算字符串中某个字符出现的次数。
例如,假设我的字符串包含:
var mainStr = "str1,str2,str3,str4";
我想求出逗号的个数,也就是3个字符。以及按逗号分隔后的单个字符串的计数,也就是4。
我还需要验证每个字符串,即str1或str2或str3或str4不应该超过,比如说,15个字符。
我需要计算字符串中某个字符出现的次数。
例如,假设我的字符串包含:
var mainStr = "str1,str2,str3,str4";
我想求出逗号的个数,也就是3个字符。以及按逗号分隔后的单个字符串的计数,也就是4。
我还需要验证每个字符串,即str1或str2或str3或str4不应该超过,比如说,15个字符。
当前回答
下面是最简单的逻辑,很容易理解
//Demo string with repeat char
let str = "Coffee"
//Splitted the str into an char array for looping
let strArr = str.split("")
//This below is the final object which holds the result
let obj = {};
//This loop will count char (You can also use traditional one for loop)
strArr.forEach((value,index)=>{
//If the char exists in the object it will simple increase its value
if(obj[value] != undefined)
{
obj[value] = parseInt(obj[value]) + 1;
}//else it will add the new one with initializing 1
else{
obj[value] =1;
}
});
console.log("Char with Count:",JSON.stringify(obj)); //Char with Count:{"C":1,"o":1,"f":2,"e":2}
其他回答
我知道这可能是一个老问题,但我有一个简单的解决方案为低水平的JavaScript初学者。
作为一个初学者,我只能理解这个问题的一些解决方案,所以我使用了两个嵌套的FOR循环来检查字符串中的每个字符,为每个发现等于该字符的字符增加一个计数变量。
我创建了一个新的空白对象,其中每个属性键是一个字符,值是每个字符在字符串中出现的次数(count)。
例子函数:
function countAllCharacters(str) {
var obj = {};
if(str.length!==0){
for(i=0;i<str.length;i++){
var count = 0;
for(j=0;j<str.length;j++){
if(str[i] === str[j]){
count++;
}
}
if(!obj.hasOwnProperty(str[i])){
obj[str[i]] = count;
}
}
}
return obj;
}
我用ramda js的解决方案:
const testString = 'somestringtotest'
const countLetters = R.compose(
R.map(R.length),
R.groupBy(R.identity),
R.split('')
)
countLetters(testString)
链接到REPL。
该函数以字符串str作为参数,并计算字符串中每个唯一字符的出现次数。结果是每个字符的键值对。
var charFoundMap = {};//object defined
for (var i = 0; i < str.length; i++) {
if(!charFoundMap[ str[i] ]) {
charFoundMap[ str[i] ]=1;
}
else
charFoundMap[ str[i] ] +=1;
//if object does not contain this
}
return charFoundMap;
}
Split与RegExp的性能
var i = 0; var split_start = new Date().getTime(); while (i < 30000) { "1234,453,123,324".split(",").length -1; i++; } var split_end = new Date().getTime(); var split_time = split_end - split_start; i= 0; var reg_start = new Date().getTime(); while (i < 30000) { ("1234,453,123,324".match(/,/g) || []).length; i++; } var reg_end = new Date().getTime(); var reg_time = reg_end - reg_start; alert ('Split Execution time: ' + split_time + "\n" + 'RegExp Execution time: ' + reg_time + "\n");
这是我的解决方案。很多解决方案已经张贴在我之前。但我喜欢在这里分享我的观点。
const mainStr = 'str1,str2,str3,str4';
const commaAndStringCounter = (str) => {
const commas = [...str].filter(letter => letter === ',').length;
const numOfStr = str.split(',').length;
return `Commas: ${commas}, String: ${numOfStr}`;
}
// Run the code
console.log(commaAndStringCounter(mainStr)); // Output: Commas: 3, String: 4
这是我的REPL