Swift Language Strings and Characters Count occurrences of a Character into a String

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Given a String and a Character

let text = "Hello World"
let char: Character = "o"

We can count the number of times the Character appears into the String using

let sensitiveCount = text.characters.filter { $0 == char }.count // case-sensitive
let insensitiveCount = text.lowercaseString.characters.filter { $0 == Character(String(char).lowercaseString) } // case-insensitive


Got any Swift Language Question?