Home > OS >  How to count number of a pattern in a string of words?
How to count number of a pattern in a string of words?

Time:12-11

This is the question

Given a dictionary of variable names where each name follows CamelCase notation, print the item containing most words. Please note, abbr, like ID , IP are considered one word. i.e. name IPAddress contains two words, IP and Address 

singleWordChecking('HelloWorldWideWeb'); the result count should be 4 singleWordChecking('HelloWWW'); the result count should be 2

below are my function on checking single world

function singleWordChecking(word) {
  let singleWordCount = 0;
  for (let i = 0; i < word.length; i  ) {
    if (
      word[i].toUpperCase() === word[i] &&
      word[i   1].toLowerCase() === word[i   1]
    ) {
      singleWordCount  = 1;
      console.log(singleWordCount);
    } else if (
      word[i].toUpperCase() === word[i] &&
      word[i   1].toUpperCase() === word[i   1]
    ) {
      return singleWordCount;
    }
  }
  return singleWordCount;
}
singleWordChecking('HelloWorldWideWeb');
singleWordChecking('HelloWWW');

i try with word[i].toUpperCase() === word[i] for verifying the first letter is capitalized, then if second letter is lowercase count 1

however when the word is 'HelloWWW' the console shows the error of

Cannot read properties of undefined (reading 'toLowerCase')
    at singleWordChecking

How do i fix this so that the edge cases can be considering into the function

CodePudding user response:

The reason you are getting the error is because you are going out of bounds of the array by doing your check for the following letter, you will need to add an extra check for:

i   1 < world.length

However, there are a couple of other issues. For one, you are returning the count when you should be incrementing the count for all capital abbreviations, also checking for 2 capital letters in a row is insufficient because abbreviations can be any length, therefore a possible solution is:

function singleWordChecking(word) {
  let singleWordCount = 0;
  let isAbbreviation = false;
  for (let i = 0; i < word.length; i  ) {
      if (word[i].toUpperCase() === word[i]) {
          if (i   1 < word.length && word[i   1].toLowerCase() === word[i   1]) {
              singleWordCount  = 1;
              isAbbreviation = false;
              
              continue;
          }
          
          if (!isAbbreviation) {
              singleWordCount  = 1;
          }
          
          isAbbreviation = true;
      }
  }
  return singleWordCount;
}
  • Related