Skip to content

Latest commit

 

History

History
40 lines (28 loc) · 1019 Bytes

2.1.4.2 CountCharInStr.md

File metadata and controls

40 lines (28 loc) · 1019 Bytes

Count Char In Str

  1. Yandex Contest

input: 1) input1 = ab, 2) input2 = aabbccd output: 4

Самый грубый способ подсчитать вхождение буквы в строку:

func howManyTimes(str: String, char: Character) -> Int {
    var letterCount = 0
    
    for letter in str {
        if letter == char {
            letterCount += 1
        }
    }
    
    return letterCount
}

Более лаконичный способ:

func howManyTimes(str: String, char: Character) -> Int {
    str.reduce(0) { $1 == char ? $0 + 1 : $0 }
}

Теперь давайте посчитаем вхождение строки в строку:

print(input1.reduce(0) { $0 + howManyTimes(str: input2, char: $1) })

2.1.4.1 Anagramma Theme | Back To iOSWiki Contents | 2.1.3.3 Generate Brackets Theme