我想使用 JavaScript 计算给定字符串中每个字符的出现次数。
例如:
var str = "I want to count the number of occurances of each char in this string";
输出应该是:
h = 4;
e = 4; // and so on
我尝试搜索谷歌,但没有找到任何答案。我想实现这样的目标;顺序无关紧要。
我想使用 JavaScript 计算给定字符串中每个字符的出现次数。
例如:
var str = "I want to count the number of occurances of each char in this string";
输出应该是:
h = 4;
e = 4; // and so on
我尝试搜索谷歌,但没有找到任何答案。我想实现这样的目标;顺序无关紧要。
这在 JavaScript(或任何其他支持地图的语言)中非常非常简单:
// The string
var str = "I want to count the number of occurances of each char in this string";
// A map (in JavaScript, an object) for the character=>count mappings
var counts = {};
// Misc vars
var ch, index, len, count;
// Loop through the string...
for (index = 0, len = str.length; index < len; ++index) {
// Get this character
ch = str.charAt(index); // Not all engines support [] on strings
// Get the count for it, if we have one; we'll get `undefined` if we
// don't know this character yet
count = counts[ch];
// If we have one, store that count plus one; if not, store one
// We can rely on `count` being falsey if we haven't seen it before,
// because we never store falsey numbers in the `counts` object.
counts[ch] = count ? count + 1 : 1;
}
现在counts
拥有每个角色的属性;每个属性的值是计数。你可以像这样输出:
for (ch in counts) {
console.log(ch + " count: " + counts[ch]);
}
更短的答案,减少:
let s = 'hello';
var result = [...s].reduce((a, e) => { a[e] = a[e] ? a[e] + 1 : 1; return a }, {});
console.log(result); // {h: 1, e: 1, l: 2, o: 1}
let str = "atul kumar srivastava";
let obj ={};
for(let s of str)if(!obj[s])obj[s] = 1;else obj[s] = obj[s] + 1;
console.log(obj)
我遍历每个字符并将其与计数一起放入嵌套对象中。如果字符已经存在于对象中,我只需增加计数。这是 myObj 的样子:
myObj = {
char1 = { count : <some num> },
char2 = { count : <some num> },
....
}
这是代码:
function countChar(str) {
let myObj= {};
for (let s of str) {
if ( myObj[s] ? myObj[s].count ++ : myObj[s] = { count : 1 } );
}
return myObj;
}
var charCount = countChar('abcceddd');
您可以在 Javascript 中使用 ES6 中的地图。在我看来,提供了一个更简洁的代码。这是我将如何去做
function countChrOccurence ('hello') {
let charMap = new Map();
const count = 0;
for (const key of str) {
charMap.set(key,count); // initialize every character with 0. this would make charMap to be 'h'=> 0, 'e' => 0, 'l' => 0,
}
for (const key of str) {
let count = charMap.get(key);
charMap.set(key, count + 1);
}
// 'h' => 1, 'e' => 1, 'l' => 2, 'o' => 1
for (const [key,value] of charMap) {
console.log(key,value);
}
// ['h',1],['e',1],['l',2],['o',1]
}
这对我来说效果很好:
function Char_Count(str1) {
var chars = {};
str1.replace(/\S/g, function(l){chars[l] = (isNaN(chars[l]) ? 1 : chars[l] + 1);});
return chars;
}
var myString = "This is my String";
console.log(Char_Count(myString));
str = "aaabbbccccdefg";
words = str.split("");
var obj = [];
var counter = 1, jump = 0;
for (let i = 0; i < words.length; i++) {
if (words[i] === words[i + 1]) {
counter++;
jump++;
}
else {
if (jump > 0) {
obj[words[i]] = counter;
jump = 0;
counter=1
}
else
obj[words[i]] = 1;
}
}
console.log(obj);
我给你非常非常简单的代码。
// Converts String To Array
var SampleString= Array.from("saleem");
// return Distinct count as a object
var allcount = _.countBy(SampleString, function (num) {
return num;
});
// Iterating over object and printing key and value
_.map(allcount, function(cnt,key){
console.log(key +":"+cnt);
});
// Printing Object
console.log(allcount);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<p>Set the variable to different value and then try...</p>
1-liner ES6 方式:
const some_string = 'abbcccdddd';
const charCountIndex = [ ...some_string ].reduce( ( a, c ) => ! a[ c ] ? { ...a, [ c ]: 1 } : { ...a, [ c ]: a[ c ] + 1 }, {} );
console.log( charCountIndex )
您可以将对象用于任务。
第 1 步 - 创建一个对象
第 2 步 - 遍历字符串
第 3 步 - 在对象中添加字符作为键和字符计数作为值
var obj={}
function countWord(arr)
{
for(let i=0;i<arr.length;i++)
{
if(obj[arr[i]]) //check if character is present in the obj as key
{
obj[arr[i]]=obj[arr[i]]+1; //if yes then update its value
}
else
{
obj[arr[i]]=1; //initialise it with a value 1
}
}
}
let newStr= "asafasdhfasjkhfweoiuriujasfaksldjhalsjkhfjlkqaofadsfasasdfas";
function checkStringOccurnace(newStr){
let finalStr = {};
let checkArr = [];
let counterArr = [];
for(let i = 0; i < newStr.length; i++){
if(checkArr.indexOf(newStr[i]) == -1){
checkArr.push(newStr[i])
let counter = 0;
counterArr.push(counter + 1)
finalStr[newStr[i]] = 1;
}else if(checkArr.indexOf(newStr[i]) > -1){
let index = checkArr.indexOf(newStr[i])
counterArr[index] = counterArr[index] + 1;
finalStr[checkArr[index]] = counterArr[index];
}
}
return finalStr;
}
let demo = checkStringOccurnace(newStr);
console.log(" finalStr >> ", demo);
function cauta() {
var str = document.form.stringul.value;
str = str.toLowerCase();
var tablou = [];
k = 0;
//cautarea caracterelor unice
for (var i = 0, n = 0; i < str.length; i++) {
for (var j = 0; j < tablou.length; j++) {
if (tablou[j] == str[i]) k = 1;
}
if (k != 1) {
if (str[i] != ' ')
tablou[n] = str[i]; n++;
}
k = 0;
}
//numararea aparitilor
count = 0;
for (var i = 0; i < tablou.length; i++) {
if(tablou[i]!=null){
char = tablou[i];
pos = str.indexOf(char);
while (pos > -1) {
++count;
pos = str.indexOf(char, ++pos);
}
document.getElementById("rezultat").innerHTML += tablou[i] + ":" + count + '\n';
count = 0;
}
}
}
此函数将每个唯一的字符放入数组中,然后在 str 中查找每个字符的外观。在我的案例中,我获取数据并将其放入
package com.company;
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
// write your code here
HashMap<Character, Integer> sHashMap = new HashMap(); // using hashMap<key , value > here key = character and value = count
String arr = "HelloWorld";
for (int i = 0; i < arr.length(); i++) {
boolean flag = sHashMap.containsKey(arr.charAt(i)); // check if char is already present
if (flag == true)
{
int Count = sHashMap.get(arr.charAt(i)); // get the char count
sHashMap.put(arr.charAt(i), ++Count); // increment the count and update in hashMap
}
else
{
sHashMap.put(arr.charAt(i), 1); //if char not present then insert into hashMap
}
}
System.out.println(sHashMap);
//OutPut would be like ths {r=1, d=1, e=1, W=1, H=1, l=3, o=2}
}
}
我用检查“空白空间”和“特殊字符”进行了尝试:
function charCount(str){
const requiredString = str.toLowerCase();
const leng = str.length;
let output = {};
for(let i=0; i<leng; i++){
const activeCharacter = requiredString[i];
if(/[a-z0-9]/.test(activeCharacter)){
output.hasOwnProperty(activeCharacter) ? output[activeCharacter]++ : output[activeCharacter] = 1;
}
}
return output;
}
我使用了 Map 对象,该 map 对象不允许您设置任何重复键,这使我们的工作变得容易。我正在检查 key 是否已经存在于 map 中,如果没有,我正在插入并将计数设置为 1,如果它已经存在,我正在获取值然后递增
const str = "Hello H"
const strTrim = str.replace(/\s/g,'') // HelloH
const strArr=strTrim.split('')
let myMap = new Map(); // Map object
strArr.map(ele=>{
let count =0
if(!myMap.get(ele)){
myMap.set(ele,++count)
}else {
let cnt=myMap.get(ele)
myMap.set(ele,++cnt)
}
console.log("map",myMap)
})
希望这可以帮助某人
function getNoOfOccurences(str){
var temp = {};
for(var oindex=0;oindex<str.length;oindex++){
if(typeof temp[str.charAt(oindex)] == 'undefined'){
temp[str.charAt(oindex)] = 1;
}else{
temp[str.charAt(oindex)] = temp[str.charAt(oindex)]+1;
}
}
return temp;
}
// Converts String To Array
var SampleString= Array.from("saleem");
// return Distinct count as a object
var allcount = _.countBy(SampleString, function (num) {
return num;
});
// Iterating over object and printing key and value
_.map(allcount, function(cnt,key){
console.log(key +":"+cnt);
});
// Printing Object
console.log(allcount);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<p>Set the variable to different value and then try...</p>
为了检查和避免空格并将大写字母转换为小写和计数,我们可以像下面那样做。
function CountNumberOfCharacters(str) {
let countObject = {};
const lowerCaseString = str.toLowerCase();
for (let char of lowerCaseString) {
if (!countObject[char] && char !== ' ') {
countObject[char] = 1;
} else if (char !== ' ') {
countObject[char] = countObject[char] + 1;
}
}
return countObject;
}
使用扩展...
运算符而不是拆分字符串.split('')
:
''.split('')
//=> ["\ud83c", "\udf2f", "\ud83c", "\udf2f", "\ud83c", "\udf63", "\ud83c", "\udf7b"]
对比
[...'']
//=> ["", "", "", ""]
对比
''.charAt(0)
//=> "\ud83c"
然后减少:
[...''].reduce((m, c) => (m[c] = (m[c] || 0) + 1, m), {})
//=> {'': 2, '': 1, '': 1}