skip to Main Content

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

3

Answers


  1. Here is the Solution that you can try

    function countWords(str) {
      // Split the string into an array of words using the split() method
      const words = str.split(" ");
    
      // Filter out empty strings (extra spaces) using filter()
      const filteredWords = words.filter(word => word.trim() !== "");
    
      // Return the length of the filtered array (number of words)
      return filteredWords.length;
    }
    
    // Example usage
    const myString = "Hello                    ";
    const wordCount = countWords(myString);
    
    console.log("Number of words:", wordCount); // Output: Number of words: 1
    
    Login or Signup to reply.
  2. Try using this function:

    const countWords = (str) => {
      return str.replace(/s+/g, ' ').split(' ').length
    }
    
    Login or Signup to reply.
  3. You have several errors:

    1. Don’t use var after the first use on a variable
    2. When the element isn’t a space, check whether it’s
      a. a first element in a string (indexcount === 0)
      b. or the previous character is a space (mystring[index – 1] === ‘ ‘)
      If so increase the word count
    var 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('trn '.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);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search