Help us understand the problem. What is going on with this article?

文字列から半角、全角両方のスペースを削除するExtensionを考える

はじめに

半角と全角の文字列が混合する配列の処理をしていたとき、各文字列からスペースを消そうとしたのですが、replacingOccurrences(of: " ", with: "")してあげただけでは当たり前ですが、全角スペースだと削除されずが残ってしまいます。

import Foundation

let array = ["あいうえ お", "abcd e"]

let fixArray = array.map { $0.replacingOccurrences(of: " ", with: "") }
//["あいうえ お", "abcde"]になる

途中まですっかりそれを見落としてたので、1回で両方削除できたら便利と思いString Extensionで作ってみよう思いました。

できたもの

import Foundation

private extension String {
    func removeWhitespace(){
        self.replacingOccurrences(of: "\u{0020}|\u{3000}", with: "", options: .regularExpression)
    }
}

let array = ["あいうえ お", "abcd e"]

let fixArray = array.map { $0.removeWhitespace() }
//["あいうえお", "abcde"]になった!!!

まとめ

もっとこうしたらいいよなどありましたらコメントいただけると幸いです。
ありがとうございました。
今年もよろしくお願いします(遅

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした