[Swift] When you want to know if the number of characters in a String matches a certain number ...

Introduction

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
  }
}

Implementation example

Simple, then △

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) $. ThiscountIsEqual 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 callcount`.

Count from the front

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

[Swift] When you want to know if the number of characters in a String matches a certain number ...
A memo when you want to clear the time part of the calendar
If you want to satisfy the test coverage of private methods in JUnit
Count the number of occurrences of a string in Ruby
If you want to recreate the instance in cloud9
If you want to know the options when configuring Ruby, see `RbConfig :: CONFIG ["configure_args "]`
What to do if you get a wrong number of arguments error in binding.pry
When you want to change the MySQL password of docker-compose
If you want to include the parent class in Lombok's @builder
What to do when you want to know the source position where the method is defined in binding.pry
When you want to check whether the contents of a property can be converted to a specific type
If you want to mock a method in RSpec, you should use the allow method for mock and the singleton method.
A trick when you want to insert a lot of line breaks and tabs when substituting a character string
I want to know the JSP of the open portlet when developing Liferay
How to find the total number of pages when paging in Java
[Swift] If you want to use a URL that includes Japanese, use addingPercentEncoding.
When you want to add a string type column with a limited length with the `rails generate migration` command
[RSpec] When you want to use the instance variable of the controller in the test [assigns is not recommended]
What to do if Operation not permitted is displayed when you execute a command in the terminal
When you want to bind InputStream in JDBI3
A note when you want Tuple in Java
When you want to use the method outside
[Swift] Use nonzeroBitCount when you want popcnt in Swift
[Ruby] When you want to replace multiple characters
[Swift] How to get the number of elements in an array (super basic)
How to get the ID of a user authenticated with Firebase in Swift
I want to recursively get the superclass and interface of a certain class
[rails] After option useful when you want to change the order of DB columns
What to do if you can't get the text of an element in Selenium
[java tool] A useful tool when you want to send the ipmsg log of PC-A to the specified PC on a regular basis.
If you make a mistake in the description location of Gem, delete Gemfile.lock once.
I want to know the answer of the rock-paper-scissors app
Summary of copy and paste commands used when you want to delete the cache in iOS application development anyway
[Java] When putting a character string in the case of a switch statement, it is necessary to make it a constant expression
Even if I want to convert the contents of a data object to JSON in Java, there is a circular reference ...
[Ruby] When you want to assign the result obtained by conditional branching to a variable and put it in the argument
How to check if the characters entered in the Swift Text Field are email addresses
[Rails] I want to display the link destination of link_to in a separate tab
Set the maximum number of characters in UITextField in RxSwift
[Swift] How to display the entered characters in Widget via UserDefaults when using WidgetKit
When you want to dynamically replace Annotation in Java8
I want you to put the story that the error was solved when you stabbed the charger in the corner of your head
# 1_JAVA I want to get the index number by specifying one character in the character string.
I want to find the MD5 checksum of a file in Java and get the result as a string in hexadecimal notation.
If hash [: a] [: b] [: c] = 0 in Ruby, I want you to extend it recursively even if the key does not exist.
[Ruby] Get in the habit of using the dup method when making a copy of a string variable
When I switched to IntelliJ, I got a lot of differences in the encoding of the properties file.
When you want to change the wording to be displayed when making a select box from enum
Use JLine when you want to handle keystrokes on the console character by character in Java
[Rails Tutorial Chapter 2] What to do when you make a mistake in the column name
When you want to reflect the Master Branch information in the Current Branch you are currently working on
What to do if you get a java.io.IOException in GlassFish
How to change a string in an array to a number in Ruby
I want to call a method and count the number
The nth and n + 1st characters of a Ruby string
A program that counts the number of words in a List
Find the number of days in a month with Kotlin
A collection of patterns that you want to be aware of so as not to complicate the code
Comparison of version strings (Java implementation) when you want to branch the process between two versions
About the method to convert a character string to an integer / decimal number (cast data) in Java
Object-oriented design that can be used when you want to return a response in form format