我需要计算字符串中某个字符出现的次数。
例如,假设我的字符串包含:
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个字符。
当前回答
s = 'dir/dir/dir/dir/'
for(i=l=0;i<s.length;i++)
if(s[i] == '/')
l++
其他回答
下面使用正则表达式测试长度。Testex确保不存在16个或更多的连续非逗号字符。如果它通过了测试,那么它将继续拆分字符串。计算逗号的数量就像计算符号减1一样简单。
var mainStr = "str1,str2,str3,str4";
var testregex = /([^,]{16,})/g;
if (testregex.test(mainStr)) {
alert("values must be separated by commas and each may not exceed 15 characters");
} else {
var strs = mainStr.split(',');
alert("mainStr contains " + strs.length + " substrings separated by commas.");
alert("mainStr contains " + (strs.length-1) + " commas.");
}
最简单的办法是…
的例子,
str = 'mississippi';
function find_occurences(str, char_to_count){
return str.split(char_to_count).length - 1;
}
find_occurences(str, 'i') //outputs 4
let str = "aabgrhaab"
let charMap = {}
for(let char of text) {
if(charMap.hasOwnProperty(char)){
charMap[char]++
} else {
charMap[char] = 1
}
}
console.log (charMap);//{a: 4, b: 2, g: 1, r: 1, h: 1}
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");
下面是最简单的逻辑,很容易理解
//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}