You may have heard that "use string.isEmpty
instead of string.count == 0
" when you want to find out if a string is empty.
The reason is that var count: Int
in String
is $ O (n) $, but var is Empty: Bool
is $ O (1) $ [^ String.isEmpty].
[^ String.isEmpty]: Reference: Why isEmpty is better than count == 0
So how do you find out if the count
of a string is equal to any number?
extension String {
func countIsEqual(to expectedCount: Int) -> Bool {
//Think here
}
}
The easiest one would be:
extension String {
func countIsEqual(to expectedCount: Int) -> Bool {
return self.count == expectedCount
}
}
let string = "Qiita"
print(string.countIsEqual(to: 1)) // -> false
print(string.countIsEqual(to: 5)) // -> true
print(string.countIsEqual(to: 10)) // -> false
but please wait a moment. I used ʻis Empty to check if the string is empty because
countis $ O (n) $. This
countIsEqual internally calls
count. If
self is at most a few characters, it's acceptable, but if
selfcan be 10 million characters, it can't be ignored. Consider a way to not call
count`.
If you don't use count
, you have to count it yourself. But if you count it yourself, you can stop counting when it exceeds ʻexpected Count`.
So now:
extension String {
func countIsEqual(to expectedCount: Int) -> Bool {
guard expectedCount >= 0 else { return false }
var countNow = 0
for _ in self {
countNow += 1
if countNow > expectedCount {
return false
}
}
return countNow == expectedCount
}
}
let string = "Qiita"
print(string.countIsEqual(to: 1)) // -> false
print(string.countIsEqual(to: 5)) // -> true
print(string.countIsEqual(to: 10)) // -> false
It ’s easy, is n’t it?
By the way, this is also $ O (n) $, but in this case $ n $ is "the smaller of count
and ʻexpected Count". Basically, if
count and ʻexpected Count
don't change that much, the first simple implementation may be better. However, if there is a possibility that a large character string will be input (whether intentional or not) due to external input, for example, and ʻexpectedCount` is expected to take a small value, click here. The implementation of is more useful.
Recommended Posts