-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy path05_charCount.swift
71 lines (58 loc) · 1.93 KB
/
05_charCount.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Count the characters
// Write a function that accepts a string, and returns how many times a specific
// character appears. Case sensitive.
// the classy way with a for-in loop
func charCount(_ input: String, char find: Character) -> Int {
var count = 0
for char in input.characters {
if char == find {
count += 1
}
}
return count
}
// introduce a constraint of no for-in or while loop
// a functional approach
func charCountNoFor(_ input: String, char check: Character) -> Int {
return input.characters.reduce(0) {
$1 == check ? $0 + 1 : $0
}
}
// an arithmetic solution
import Foundation
func charCountWithRemoval(_ input: String, char check: String) -> Int {
let newInput = input.replacingOccurrences(of: check, with: "")
return input.characters.count - newInput.characters.count
}
//Swift 4
func charCount2(_ input: String, char check: Character) -> Int {
var count = 0
input.forEach { if $0 == check { count += 1 }}
return count
}
func charCountNoFor2(_ input: String, char check: Character) -> Int {
return input.reduce(0) {
$1 == check ? $0 + 1 : $0
}
}
// Test Cases
charCount("hello", char: "h") // 1
charCount("hello", char: "l") // 2
charCount("hello", char: "q") // 0
charCount("hello", char: "H") // 0
charCountNoFor("hello", char: "h") // 1
charCountNoFor("hello", char: "l") // 2
charCountNoFor("hello", char: "q") // 0
charCountNoFor("hello", char: "H") // 0
charCountWithRemoval("hello", char: "h") // 1
charCountWithRemoval("hello", char: "l") // 1
charCountWithRemoval("hello", char: "q") // 1
charCountWithRemoval("hello", char: "H") // 1
charCount2("hello", char: "h") // 1
charCount2("hello", char: "l") // 2
charCount2("hello", char: "q") // 0
charCount2("hello", char: "H") // 0
charCountNoFor2("hello", char: "h") // 1
charCountNoFor2("hello", char: "l") // 2
charCountNoFor2("hello", char: "q") // 0
charCountNoFor2("hello", char: "H") // 0