0

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.

Joseph Cho
  • 4,033
  • 4
  • 26
  • 33
  • What is your goal? Is your goal know all the number of occurrences for each letter? You could use a `NSCountedSet` for that. Or just know frequency for one letter? – Larme Sep 04 '18 at 16:17
  • get the amount of occurance of a certain characther in a string in one simple command – jessyjannis Sep 04 '18 at 16:44
  • Possible duplicate of [Swift :: Number of occurrences of substring in string](https://stackoverflow.com/questions/31746223/swift-number-of-occurrences-of-substring-in-string) – ivan_pozdeev Sep 05 '18 at 01:20

4 Answers4

4

One possible solution:

let string = "xhjklghxhjkjjklxjhjkjxx"

print(string.filter({ $0 == "x" }).count)
// prints: 5
Alex Nazarov
  • 199
  • 6
0

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 }
vadian
  • 274,689
  • 30
  • 353
  • 361
0

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
    }
}
James Bucanek
  • 3,299
  • 3
  • 14
  • 30
  • This won't work for characters with more than one unicode value. It will count it twice or more try `` – Leo Dabus Sep 04 '18 at 17:53
  • That's true, but the OP asked to count the number of x's and "x" has a single Unicode scalar value. However, I'll modify the answer with one that would work for an single Character. – James Bucanek Sep 04 '18 at 22:07
0

great responses

i went with

appWindow.title.components(separatedBy: "​x").count - 1
ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
  • 3
    It's great that you add your own solution! However it's a bit confusing that you write "great responses, I went with", because it sounds like you're thanking the other answerers and state which one you chose. In the review queue we don't see other answers, so on first glance your answer looks like a "thank you" post. Apart from that I find puzzling that you now commented "no one came up with a proper response", which conflicts with the fact that you have accepted another answer. It also implies that the "great responses" was sarcastic, which isn't nice. I suggest to edit your answer. – Max Vollmer Sep 05 '18 at 00:50