【发布时间】:2020-01-30 12:31:40
【问题描述】:
在这里发布一个问题 ~find all ~4 个字母的单词在一个字符串 ~algorithm site:stackoverflow.com google 没有返回任何积极的结果。
问题: 编写一个函数,接收一串单词并返回 4 个字母的个数。输入参数 'sentence' 是一个字符串,单词由空格分隔,没有标点符号。
到目前为止,我有这样的代码:
func fourLetters(sentence: String) -> Int {
var targetNames = 0
var letterCount = 0
for letter in sentence {
if letter != " " {
letterCount += 1
} else {
print ("space found") // tech line
print (letterCount) // tech line
if letterCount == 4 {
targetNames += 1
letterCount = 0
}
letterCount = 0
}
}
print(targetNames) // tech line
return targetNames
}
问题: 该算法现在不考虑字符串的最后一部分给出无效的 4 个字母单词数。考虑我们有句子:“Good Night Lil Peep”将返回 1,尽管显然有两个 4 出纳词。我错过了什么?似乎循环完全忽略了最后一个词。
repl.it 链接方便运行:https://repl.it/@DmitryAksyonov/4-lettered-names
感谢您的帮助! 问候
【问题讨论】:
-
@KeshuR.: 不,代码审查是为了审查(和改进)“工作正常据作者所知的代码。”
-
单行:
return sentence.split(separator: " ").filter { $0.count == 4 }.count -
@MartinR 我正要评论
sentence.split{$0.isWhitespace}.filter{$0.count == 4}.count" -
@LeoDabus:我们还在等待
count(where:)... :) -
@LeoDabus:在 Swift 5.2 中你可以做到
split(whereSeparator: \.isWhitespace):)