Count consonants in a string javascript

The main problem in counts lies within your conditions.

You're increasing the number of consonants whenever one of the conditions fail [that's what || does, known as the OR operator]. So whenever a character !== "a" OR !== "e", you're increasing the count, which is wrong. [Imagine that a is !== 'e', so you're counting a as a consonant].

Change the || binary operator to && [AND]; this way, you're only increasing the consonant count whenever the current character str[i] is not among the values you're verifying for [a, e, i, o, u, ' '].

As others pointed out, you're also likely to run into an error as the max value of i should be Length-1.

There also other problems you need to consider:

  • What happens when the character is an uppercase letter?
  • What happens when the character is a punctuation mark or a number?

For a beginner, this may not be relevant, but it's well worth getting these techniques under your skin: It's more readable to create an array that contains all of the value you're verifying for ["a","e", etc] and then, for each char in the source string, just verify if array.indexOf[str[i]] >= 0 [which means that the character is included in the array].

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Given a string, count total number of consonants in it. A consonant is a English alphabet character that is not vowel [a, e, i, o and u]. Examples of constants are b, c, d, f, g, ..

    Examples : 

    Input : abc de
    Output : 3
    There are three consonants b, c and d.
    
    Input : geeksforgeeks portal
    Output : 12

     1. Iterative Method 

    C++

    #include

    using namespace std;

    bool isConsonant[char ch]

    {

        ch = toupper[ch];

        return ![ch == 'A' || ch == 'E' ||

                ch == 'I' || ch == 'O' ||

                ch == 'U'] && ch >= 65 && ch

    Javascript

          function isConsonant[ch]

          {

            ch = ch.toUpperCase[];

            console.log[ch];

            return [

              ![ch == "A" || ch == "E" || ch == "I" || ch == "O" || ch == "U"] &&

              ch.match[/[A-Z]/i]

            ];

          }

          function totalConsonants[str] {

            var count = 0;

            for [var i = 0; i < str.length; i++]

              if [isConsonant[str[i]]] ++count;

            return count;

          }

          var str = "abc de";

          document.write[totalConsonants[str]];

        

    Time Complexity: O[n], where n is the length of the string
    Auxiliary Space: O[1]

     2. Recursive Method 

    C++

    #include

    using namespace std;

    bool isConsonant[char ch]

    {

        ch = toupper[ch];

        return ![ch == 'A' || ch == 'E' ||

                ch == 'I' || ch == 'O' ||

                ch == 'U'] && ch >= 65 && ch

    Chủ Đề