如何在 swift 中的字符串数组中查找某个字母的出现次数

How to find occurences of a lettter in the string array in swift

我是尝试实现此逻辑的初学者,任何人都可以提出逻辑建议。

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
}

但是我不明白 components(separatedBy:) 里面的逻辑到底是什么?我的意思是没有更高的功能我们怎么能在这里实现逻辑。

尝试这样的事情:

 func findLetterOccurence(letter: String) {
    var count = 0
    for word in array { count += word.filter{ String([=10=]) == letter}.count }
    print("--> \(letter) occured in \(count) times")
}

如果不区分大小写,则必须进行调整,例如:

func findLetterOccurence(letter: String) {
    var count = 0
    for word in array { count += word.filter{ String([=11=]).lowercased() == letter.lowercased()}.count }
    print("--> \(letter) occured in \(count) times")
}

添加此扩展以查找字符串中后者的出现

extension 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")
    }

几种方式。

    @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 [=10=].lowercased() == letter.lowercased() { count += 1} } )
    
    print("\(letter) occured in \(count) times")
    
    return count
}

你也可以做一个敏感的比较,不要管外壳 通过说

array.joined().forEach({ if String([=11=]) == 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 [=12=] 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) {
           [=12=] += .lowercased() == letter.lowercased() ? 1 : 0
        }
        print("\(letter) occured in \(count) times")
    
        return count
    }