Counting words in a string - camelCase

Viewed 1343

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
}
3 Answers

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.

You are counting the uppercase char and the string oneTwoThree has only two uppercase letters. So, the output will be 2.

Instead you can use regular expression to split the string at uppercase.

const s = 'oneTwoThree';

console.log(s.split(/(?=[A-Z])/g).length);

You could use regex to replace all the lower case alphabets and then count the remaining.

let string1 = "saveChangesInTheEditor";
let string2 = "oneTwoThree";
//For empty Strings
let string3 = "";

function camelcase(s) {
  return (s ? (s.trim().replace(/[^A-Z]/g, "").length + 1) : 0);
}

console.log(camelcase(string1));
console.log(camelcase(string2));
console.log(camelcase(string3));

The below code snippet is for array, you could use this if you want to pass an array. The function will return an array with the world count in the same order.

let arr = ["saveChangesInTheEditor", "oneTwoThree", ""]

function camelcase(s) {
  if (Array.isArray(s)) {
    let camelCase = [];
    for (const string of s) {
      camelCase.push((string ? (string.trim().replace(/[^A-Z]/g, "").length + 1) : 0));
    }
    return camelCase;
  } else {
    return (s ? (s.trim().replace(/[^A-Z]/g, "").length + 1) : 0);
  }
}

console.log(camelcase(arr));

Related