-2

I am trying to create a function with two parameters that will count how times a character repeats in a given string. I have my code below but it is not working properly. Also, I am trying to make it a non-recursive function. Can anyone help me with that?

function count(char,word) {
  var a,b;
  a= char
  b= word
  c= b.indexof(a)
  return c
}

count('a','apple')
sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Gonzi
  • 1
  • 1
  • check here http://stackoverflow.com/questions/11649255/how-to-count-the-number-of-occurences-of-each-item-in-an-array. – jsh Oct 05 '15 at 23:31
  • **count how many times a character repeats**. Not sure why the answers missed this. – Travis J Oct 05 '15 at 23:41
  • @Oriol - I believe the question is how many times does the character repeat in the word. For example, l in allegedly should not be 3. – Travis J Oct 05 '15 at 23:50
  • Repetition means sequential, occurrence means total. 'l' occurs three times, but repeats twice at one point. – Travis J Oct 05 '15 at 23:59
  • @TravisJ I don't think "repetitions" are necessarily "consecutive repetitions". – Oriol Oct 06 '15 at 00:00
  • @TravisJ - You're making that up as an interpretation of the question. The question does not say what you think it means. Perhaps the question is not entirely clear in that regard, but it does NOT say what you think it means. You seems to think that the way the OP uses "repeats" means `occurrences - 1`, but that's just your GUESS. There are other legit interpretations of the question too such as "how many occurrences of a character are there". – jfriend00 Oct 06 '15 at 00:00
  • @jfriend00 - Not occurrences -1, the count of repetitions. For example, in "000101010001010101000" how many repetitions of "0" are there? 3. How many occurrences of "0" are there? 14. – Travis J Oct 06 '15 at 00:02
  • @Gonzi - Do you mean how many times is a given character present in a word? – jfriend00 Oct 06 '15 at 00:02
  • @TravisJ - that's just your guess at what this question means which is different than EVERYONE else's interpretation of the question. Until the OP responds to our questions, your guess is no more valid than what all the answers have provided. – jfriend00 Oct 06 '15 at 00:03
  • If I have misinterpreted the question I will change my position here. However, the word "repetition" is well defined. – Travis J Oct 06 '15 at 00:03
  • @Gonzi - did one of these solutions work for you? Did you get an answer to your question? If so, please mark the answer that you see as the best answer by clicking the green checkmark to the left of that answer to indicate to the community that your question has been answered and you will also earn some reputation points (which will eventually earn you more privileges here) for following the proper procedure. – jfriend00 Oct 15 '15 at 03:10

7 Answers7

5

To count the occurrences of a string inside another one, you can split the latter using the former as the separator, and then use length to count the items of the returned array.

function count(char, word) {
  return word.split(char).length - 1;
}
Oriol
  • 274,082
  • 63
  • 437
  • 513
4

If what you mean by your question is "how many occurrences of a given character are there in a word", then there are several possibilities. You can loop calling .indexOf(), you can let a regex find all the matches or you can just iterate through the string manually comparing.

If you meant something different by your question, please clarify the question.

Here are some possibilities:

function count(char, word) {
        var cntr = 0;
        var pos = 0;
        while ((pos = word.indexOf(char, pos)) !== -1) {
            ++cntr;
            ++pos;
        }
        return cntr;
    
    }

    var cnt = count('a','apple');
    document.write(cnt + "<br>");

    cnt = count('p','apple');
    document.write(cnt);

Or, you could use a regex if your character is not a special regex character:

     function count(char, word) {
         var cnt =  word.match(new RegExp(char, "g"));
         return cnt ? cnt.length: 0;
     }

     var cnt = count('p', 'apple');
     document.write(cnt);

Or, you could just iterate through the string and manually count:

function count(char, word) {
    var cnt = 0;
    for (var i = 0; i < word.length; i++) {
        if (word.charAt(i) === char) {
            ++cnt;
        }
    }
    return cnt;
}

var cnt = count('p', 'apple');
document.write(cnt);
jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

This is a very simple loop that iterates through the word, counting the instances of ch.

function count(ch,word) {
  var i,count = 0;
  for(i = 0; i < word.length; i++) {
    if (word[i] === ch) count++;
  }
  return count;
}

console.log(count('p','apple'));
user2182349
  • 9,569
  • 3
  • 29
  • 41
0

You need loops:

function count(c, word) {
  var i = 0;
  var arr = word.split(''); //break into array
  var a;
  while (arr.length) { //until array runs out of letters
    a = arr.pop(); // pull out one by one
    if (a === c) // got match
      i++;
  }
  return i;
}

alert(count('a', 'apple'));
0

The simplest way would probably be just looping through the input. Like this:

function count(char,word) {
  var count = 0;
  for(var i = 0; i < word.length; i++)
  {
    if(word.charAt(i) === char)
      count++;
  }
  return count;
}
ddsnowboard
  • 922
  • 5
  • 13
0

Here's a way you can do this with a regular expression:

function countLetter(letter,word) {
  var regexp = New RegExp(letter, 'g') //searches word for letter
  var arr = word.match(regexp);        //finds the letter within the word,
  return arr == null ? 0 : arr.length;
}                                      //sticks that letter into arr for each time it
                                       //appears in the word

console.log(countLetter('a','apple a a a '));
//arr = ['a', 'a', 'a', 'a'], arr.length = 4
console.log(countLetter('p','apples'));
//arr = ['p','p'] arr.length = 2

Hope this helps!

dmwong2268
  • 3,315
  • 3
  • 19
  • 20
0

I would go with an accumulator function for simply counting occurrences

function count(char,word) {
    return [].reduce.call(word,function(p,c){
        return p += char == c ? 1 : 0;
    },0);
}

However, that would just be for totals. In order to count "in a row" is much different and would require tracking the repetitions

function count(char,word) {
    var total = 0;
    var max = 0;
    [].reduce.call(word.substr(1,word.length),function(p,c){
        if(p == c && c == char){ total++ }else{
            if( total > max ) max = total;
            total = 0;
        }
        return c;
    },word[0]);
    return max > 0 ? max + 1 : 0;
}
Travis J
  • 81,153
  • 41
  • 202
  • 273