【Swift】 replacingOccurrences(of:with:)の使いかた

まずはApple公式ドキュメントから。
1 2 |
func replacingOccurrences(of target: String, with replacement: String) -> String |
Returns a new string in which all occurrences of a target string in the receiver are replaced by another given string.
ポイント
replacingOccurrencesを使えばstring型の値を置換できる。
of target => 置換対象の文字列
with replacement => 置換したい文字列
サンプルで使ってみます。
1 2 3 4 5 |
import Foundation var str = "Hello, playground" print(str.replacingOccurrences(of: "Hello", with: "Hi")) //"Hi, playground" |
【まとめ】 replacingOccurrences(of:with:) の使いかた

文字列の置換に便利。積極的に使っていきたい。
参考にした記事: