Итак, я написал код, который будет обнаруживать все слова, содержащиеся в предложении. Я бы обнаруживал только слова и игнорировал пробелы, а это означает, что даже если в строке есть пустые места, я бы не стал их считать. Но результат не тот, что я ожидал. Вот код:
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.info(words);
Таким образом, этот код на самом деле поможет любому, кто захочет узнать все слова в строке, игнорируя все пробелы. Таким образом, даже если бы у вас было всего одно слово в строке и еще много пробелов, результат был бы 1. Но я получаю странные результаты. пожалуйста помоги
добавил пояснение к моему ответу
str.split(" ").filter(x => !!x)
Вот решение, которое вы можете попробовать
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.info("Number of words:", wordCount); // Output: Number of words: 1
Спасибо за этот код, но мне хотелось бы знать, почему мой код не работает.
Попробуйте использовать эту функцию:
const countWords = (str) => {
return str.replace(/\s+/g, ' ').split(' ').length
}
У вас есть несколько ошибок:
var
после первого использования переменной.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.info(words);
Рассмотрите возможность использования конечного автомата:
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.info(words);
Вы также можете использовать регулярное выражение:
var mystring = ` Hello
World `;
const words = mystring.match(/(?<=\s|^)(?=\S)/g).length;
console.info(words);
Чего вы пытаетесь достичь с помощью проверок
element[indexcount + 1] != " "
?