1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Swift】文字列から特定の文字を削除

Last updated at Posted at 2021-11-08

Swiftで文字列から特定の文字を削除。

例えば郵便番号や電話番号、検索ワードで入力されてほしくない、半角スペースや全角スペース、伸ばし棒などを取り除きたい時などに使用。

//半角と全角の空白
var str1 = "文房具 消しゴム    おすすめ"
//半角と全角の伸ばし棒
var str2 = "0120-0000ー0000"

let delete_str: Set<Character> = ["-","ー"," "," "]
str1.removeAll(where: { delete_str.contains($0) })
str2.removeAll(where: { delete_str.contains($0) })

delete_strで設定した文字(単数でも複数でも可)がすべて削除されます。

参考

Swiftのお役立ち情報

1
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?