Coding Problem how many words

Abhijit chakra
2 min readFeb 4, 2022

Here is the question like this

A sentence is made up a group of words . each word is a sequence of letters,(‘a’-’z’,’A’-’Z’),that may contain one or more hypens and may end in punctuation mark: period(.),comma(,),question mark(?), or exclamation point(!).words will be separated by one or more white space characters .Hypens join two words into into one and should be retained while the other punctuation marks should be striped , determine the number of words in a given sentence .

//A sentence is made up a group of words . each word is a sequence of letters,(‘a’-’z’,’A’-’Z’),that may contain one or more hypens and may end in punctuation mark: period(.),comma(,),question mark(?), or exclamation point(!).words will be separated by one or more white space characters .Hypens join two words into into one and should be retained while the other punctuation marks should be striped , determine the number of words in a given sentence .

function howmany(sentence) {
//remove all higpens
sentence = sentence.replace(“-”, “”)
//convert the string the array based on white space
sentence = sentence.split(‘ ‘)
//initialize the word count
let wordCount = 0
let endOfString;
let fullString;

//iterate over the string array
for (let i = 0; i < sentence.length; i++) {
console.log(sentence[i])

if (sentence[i].length = 0) {
return 0
}
if (sentence[i].length == 1) {
fullString = sentence[i]
endOfString = fullString
} else {
fullString = sentence[i].substring(0, sentence[i].length — 1)
endOfString = sentence[i].substring(sentence[i].length — 1, sentence[i].length)
}

//if()
// console.log(fullString)
if (!fullString.match(/\W/) && !hasNumber(fullString) && endOfString.match(/\W/) && !hasNumber(endOfString)) {
isWord = true
wordCount++

} else if (!fullString.match(/\W/) && !hasNumber(fullString) && !endOfString.match(/\W/) && !hasNumber(endOfString)) {
isWord = true
wordCount++
}
}
return wordCount
}

function hasNumber(myString) {
return /\d/.test(myString);
}

console.log(howmany(“How many eggs are in a half-dozen, 13?”))

--

--