9
6

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 2020-10-07

複数の文字列を置換する方法

単体の文字列置換

文字列を置換するには、replacingOccurrences が使用できます。

// 置換前
var str: String = "みかん"

// 置換
var newStr = str.replacingOccurrences(of: "み", with: "オ")

// 置換後
print(newStr) //オかん

複数の文字列置換

replacingOccurrences を使用する前に、
辞書を作成しておくと複数の文字列を置換することが可能です。

// 置換前
var str = "ABCDEF"

var newStr: String {

   // 辞書作成
    let dictionary = ["A": "置","B": "換","C": "で","D": "き","E": "た","F": "よ"]
    
    // 置換
    return dictionary.reduce(str) { $0.replacingOccurrences(of: $1.key, with: $1.value) }

}

// 置換後
print(newStr)  // "置換できたよ"

※ reduce については以下の記事がわかりやすいです。
Swiftにおけるreduceの使い方

9
6
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
9
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?