Count of occurrences in a String

Asked

Viewed 3,064 times

6

How do I write a function that receives a as argument, and returns an object listing the number of occurrences in the current string ?

Currently I have this:

charCount("hello");
// {
//  "h": 1,
//  "e": 1,
//  "l": 2,
//  "o": 1
// }

//It should ignore capitalization

charCount("AaBbC")
// {
//  "a": 2,
//  "b": 2,
//  "c": 1,
// }
  • What have you been able to do so far? Edit the question and enter the code so we can help you.

3 answers

6


The steps you need the function to take:

  • separate the string into pieces
  • create an object
  • assigns the object a property for each letter
  • count how many occurrences

This function could be like this (put optional count or not with large/small letters, by default not counting):

function charCount(str, keepCase) {
    if (!keepCase) str = str.toLowerCase();
    var obj = {};
    for (var i = 0; i < str.length; i++) {
        if (!obj[str[i]]) obj[str[i]] = 0;
        obj[str[i]]++;
    }
    return obj;
}

and testing would be:

var a = charCount("hello");
var b = charCount("AaBbC");
var c = charCount("AaBbC", true); // contando com letras grandes!

console.log(a, b); // Object {h: 1, e: 1, l: 2, o: 1} Object {a: 2, b: 2, c: 1}
console.log(c); // Object {A: 1, a: 1, B: 1, b: 1, C: 1}

jsFiddle: http://jsfiddle.net/Sergio_fiddle/hexn3twf/

3

See the roles of the PHP.JS project

It is a project that translates functions from PHP to Javascript.

In PHP there is a function count_chars, which is translated into Javascript on the project website: http://phpjs.org/functions/count_chars/

To see the result of the snippet, open the browser console. In Google Chrome, press CTRL+SHIFT+I

function count_chars(str, mode) {
  //  discuss at: http://phpjs.org/functions/count_chars/
  // original by: Ates Goral (http://magnetiq.com)
  // improved by: Jack
  // bugfixed by: Onno Marsman
  // bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  //    input by: Brett Zamir (http://brett-zamir.me)
  //  revised by: Theriault
  //   example 1: count_chars("Hello World!", 3);
  //   returns 1: " !HWdelor"
  //   example 2: count_chars("Hello World!", 1);
  //   returns 2: {32:1,33:1,72:1,87:1,100:1,101:1,108:3,111:2,114:1}

  var result = {},
    resultArr = [],
    i;

  str = ('' + str)
    .split('')
    .sort()
    .join('')
    .match(/(.)\1*/g);

  if ((mode & 1) == 0) {
    for (i = 0; i != 256; i++) {
      result[i] = 0;
    }
  }

  if (mode === 2 || mode === 4) {

    for (i = 0; i != str.length; i += 1) {
      delete result[str[i].charCodeAt(0)];
    }
    for (i in result) {
      result[i] = (mode === 4) ? String.fromCharCode(i) : 0;
    }

  } else if (mode === 3) {

    for (i = 0; i != str.length; i += 1) {
      result[i] = str[i].slice(0, 1);
    }

  } else {

    for (i = 0; i != str.length; i += 1) {
      result[str[i].charCodeAt(0)] = str[i].length;
    }

  }
  if (mode < 3) {
    return result;
  }

  for (i in result) {
    resultArr.push(result[i]);
  }
  return resultArr.join('');
}


/**
Exemplo de uso
*/
var rs = count_chars('foo bar', 1);

/**
O resultado retorna o valor em "bytecode", por isso, é preciso converter para o caracter correspondente. 
Aqui usamos String.fromCharCode()
*/
for (var k in rs) {
    console.log(k, String.fromCharCode(k), rs[k]);
};

3

I created a function that returns the maximum number of occurrences of a character in a string and called count(), after this I declared a go through the whole string and taking the maximum of occurrences of each one, in this arose the problem of repeating character information, and to solve this problem I created an object that is the return of the function to take all occurrences and not repeat-Las, look how it turned out:

Example:

var str = 'Hello World';

function charCount(str) {

  function count(string, char) {
    var re = new RegExp(char, "gi");
    return string.match(re).length;
  }

  var result = {};
  for (var i = 0; i < str.length; i++) {
    result[str[i]] = count(str, str[i]);
  }

  return result;
}

document.write(JSON.stringify(charCount(str)));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.