我是初学者,尝试实现这个逻辑,谁能建议这个逻辑?
func findLetterOccurence(Letter: String){
let array = ["Data", "program", "questions", "Helpful"]
///Logic to find the given letter occurences in string array
print("(Letter) occured in (count) times")
}
预期输出:a出现在3次
我试过了:
var count = 0
for i in array {
var newArray.append(i)
count = components(separatedBy: newArray).count - 1
}
但是我不明白组件内部的逻辑到底是什么(separatedBy:) ?我的意思是,如果没有更高的函数,我们怎么能在这里实现逻辑呢?
有几种方法
@discardableResult func findLetterOccurence(letter: String) -> Int {
let array = ["Data", "program", "questions", "Helpful"]
var count = 0
// here we join the array into a single string. Then for each character we check if the lowercased version matches the string lowercased value.
array.joined().forEach({ if $0.lowercased() == letter.lowercased() { count += 1} } )
print("(letter) occured in (count) times")
return count
}
你也可以做一个敏感的比较,而不使用大小写说
array.joined().forEach({ if String($0) == letter { count += 1} } )
另一种方式是
//here our argument is a character because maybe we just want to search for a single letter.
@discardableResult func findLetterOccurence2(character: Character) -> Int {
let array = ["Data", "program", "questions", "Helpful"]
//again join the array into a single string. and reduce takes the `into` parameter and passes it into the closure as $0 in this case, and each element of the string gets passed in the second argument of the closure.
let count = array.joined().reduce(into: 0) {
$0 += $1.lowercased() == letter.lowercased() ? 1 : 0
}
print("(letter) occured in (count) times")
return count
}
试试这样:
func findLetterOccurence(letter: String) {
var count = 0
for word in array { count += word.filter{ String($0) == letter}.count }
print("--> (letter) occured in (count) times")
}
如果你想要不区分大小写,你必须调整,像这样:
func findLetterOccurence(letter: String) {
var count = 0
for word in array { count += word.filter{ String($0).lowercased() == letter.lowercased()}.count }
print("--> (letter) occured in (count) times")
}
添加此扩展以查找字符串
中出现的laterextension String {
func numberOfOccurrencesOf(string: String) -> Int {
return self.components(separatedBy:string).count - 1
}
}
用于数组
func findLetterOccurence(Letter: String){
let array = ["Data", "program", "questions", "Helpful"]
var number = 0
for str in array{
var l = Letter
// uncomment it to use code for upper case and lower case both
// l = str.lowercased()
number = number + str.numberOfOccurrencesOf(string: l)
}
print("(Letter) occured in (number) times")
}