Count of occurrences in a String

5

As I write a function that receives a

asked by anonymous 12.12.2015 / 16:49

3 answers

5

The steps you need the function to do:

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

This function could be like this (I have optional 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: link

    
12.12.2015 / 19:28
2

See the PHP.JS project functions

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

In PHP there is the count_chars function, which is translated into JavaScript on the project site: link

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(/(.)*/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]);
};
    
12.12.2015 / 17:21
2

I created a function that returns the maximum number of occurrences of a character in a string and called it count() , after that I declare a for going through the entire string and taking the maximum number of occurrences of each one, character information, and to solve this problem I created an object that is the return of the function to take all the occurrences and not to repeat them, see how it was:

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)));
    
12.12.2015 / 18:52