1
1

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 3 years have passed since last update.

【Swift】文字列の部分置換を行う

Last updated at Posted at 2022-04-16

macOS: 12.3.1(21E258) Swift: 5.6 Xcode: 13.3.1 (13E500a)

はじめに

APIからのレスポンスとして受け取った文字列を部分的に置換したい...ということがありました。
今回はその時に使用した、replacingOccurrences(of:with:)メソッドを紹介します。

replacingOccurrences(of:with:)メソッド

公式ドキュメントより、下記のように宣言されていることが確認できます。

func replacingOccurrences(of target: String, with replacement: String) -> String

パラメータ

  • target: 置換前の文字列
  • replacement: 置換後の文字列

実行すると新しい文字列が得られます。

使用例

replacingOccurrences(of:with:)メソッドはFoundationで提供されています。
使用する際は、Foundationをインポートしておきましょう。

下記では、"-"(ハイフン)を" "(半角スペース)に置換する操作を行っています。

サンプルコード

swift 5.6
import Foundation

let original = "Tap-Lele" //変換前の文字列
print("変換前:", original)

let replaced = original.replacingOccurrences(of: "-", with: " ") // "-"を" "に置換
print("変換後:", replaced)

実行結果

変換前: Tap-Lele
変換後: Tap Lele

さいごに

今回は文字列の部分置換ができるreplacingOccurrences(of:with:)メソッドを紹介しました。
今後も備忘録として学んだことを記事にしていこうと思いますので、よろしくお願いします。

参考記事

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?