jessyjannis
jessyjannis

Reputation: 15

Better way to find occurrence amount of a certain character in a string

I'm using this to find the number of occurrences in a character of a string

String(appWindow.title.count - appWindow.title.replacingOccurrences(of: "x​", with: String()).count)

Is there a way to do it with a simpler command?

I tried to split it but it always says 1 even when the char isn't there.

Upvotes: 0

Views: 104

Answers (4)

jessyjannis
jessyjannis

Reputation: 15

great responses

i went with

appWindow.title.components(separatedBy: "​x").count - 1

Upvotes: 0

James Bucanek
James Bucanek

Reputation: 3439

Why can you simply do something like this?

let str = "Hello, playground"
let characters = CharacterSet(charactersIn: "o")

var count = 0
for c in str.unicodeScalars {
    if characters.contains(c) {
        count += 1
    }
}

print("there are \(count) characters in the string '\(str)'")

But, as @Leo Dabus pointed out, that would only work for simple Unicode characters. Here's an alternative that would work for counting any single character:

for c in str {
    if c == "o" {
        count += 1
    }
}

Upvotes: 0

vadian
vadian

Reputation: 285072

You could use reduce, it increments the result($0) if the character($1) is found

let characterCount = appWindow.title.reduce(0) { $1 == "x" ? $0 + 1 : $0 }

Upvotes: 0

Alex Nazarov
Alex Nazarov

Reputation: 199

One possible solution:

let string = "xhjklghxhjkjjklxjhjkjxx"

print(string.filter({ $0 == "x" }).count)
// prints: 5

Upvotes: 4

Related Questions