Search code examples
javascriptstringalgorithmcountfor-of-loop

Counting words in a string - camelCase


Given s, print the number of words in on a new line. For example, s = oneTwoThree . There are 3 words in the string.

I know I'm finding the letters that are capitalized, but not sure if I'm counting the words correctly.

What am I missing?

Input

saveChangesInTheEditor

Output

5

Right now, I'm getting 0.

function camelCase(s) {

   let count = 0;

   for(let i of s){

    if(s.charAt(i) === s.charAt(i).toUpperCase()){

      count++

    }
   }
   return count
}

Solution

  • Just two problems I can see. You want let i in s, not let i of s. (The former gives you the index whereas the latter gives you the actual letter at that position).

    The second problem is you probably want to start your count at 1 since the first word will always start with a lowercase letter.

    function camelcase(s) {
       let count = 1;
       for(let i in s){
        if(s.charAt(i) === s.charAt(i).toUpperCase()){
          count++
        }
       }
       return count
    }
    
    console.log(camelcase("oneTwoThree"));

    If this is a coding challenge, you might want to account for edge cases. For example, what should the answer be for an empty string? Should you test explicitly for that? Will there be spaces, numbers, or special characters in the input string? That might be an issue with this current logic.