So ive written a code which would detect all the words that are there in a sentence. I would only detect the words and would ignore the spaces, which means even if there are empty spaces in the string i would not count them. But the result are not what i expected. Here is the code :
var mystring = "Hello World"
var indexcount = 0
var words = 0
for (element of mystring) {
if (element == " " || element[indexcount + 1] != " " || element[indexcount - 1] != " ") {
var words = words + 1
var indexcount = indexcount + 1
} else {
indexcount = indexcount + 1
}
}
console.log(words);
So this code would actually help anyone who would want to know all the words that are there in a string, ignoring all the spaces. So even if you had just a single word within a string and a lot of spaces still, the result would be 1. But i am getting weird ouputs. please help
You have several errors:
var
after the first use on a variablevar mystring = "Hello World"
var indexcount = 0
var words = 0
for (var element of mystring) {
if (element !== " " && (indexcount === 0 || mystring[indexcount - 1] === " ")) {
words = words + 1;
}
indexcount = indexcount + 1;
}
console.log(words);
Consider using a state machine:
var mystring = ` Hello
World `;
const spaces = new Set('\t\r\n '.split('')); // detect spaces with a set
let words = 0;
let inWord = false; //whether we are inside of a word or not
for(const char of mystring){
if(spaces.has(char)){
inWord = false;
} else if(!inWord) {
words++;
inWord = true;
}
}
console.log(words);
You could also use a regex:
var mystring = ` Hello
World `;
const words = mystring.match(/(?<=\s|^)(?=\S)/g).length;
console.log(words);