Самое короткое будет использовать: str1.split(/\s+/).length
Но на всякий случай любой новичок захочет сделать это с basi c l oop, вот оно:
let str1: string = 'I love stackoverflow'
let numberOfSpaces: number = 0
for (let index = 1; index <= str1.length; index++) {
let lastChar: string = ''
let currentChar: string = ''
currentChar = str1.charAt(index)
lastChar = str1.charAt(index - 1)
if (currentChar === " " && lastChar !== " ") {
numberOfSpaces = numberOfSpaces+ 1
}
else if (currentChar === " " && lastChar === " ") { // This is a test String.
numberOfSpaces = numberOfSpaces + 0
}
//I have not added an else statement for the case if both current char and last char are not whitespaces.
//because I felt there was no need for that and it works perfectly.
}
const finalNumberOfWords: number = numberOfSpaces + 1
console.log(`Number of words final are = ${finalNumberOfWords}`)
Так что это может выглядеть как метод подсчета пробелов, да, но это не так, посторонние пробелы [пробел с пробелом]. for loop
работает по всей длине строки. Он сравнивает символ в текущей позиции str1[index]
и его предыдущий индекс. Если оба являются пробелами, они не будут учитываться, но если предыдущий символ был ненулевым, а текущий пустым, счетчик увеличивается на единицу.
И, наконец, мы добавляем 1 к счетчику для отображения количества слов.
Вот скриншот: