どうも、ちょげ(@chogetarou)です。
文字列の特定の文字を、別の文字に置換する方法を紹介します。
方法

文字列の特定の文字を置換するには、replaceOccurrencesメソッドを使います。
まず、文字列からreplaceOccurrencesメソッドを呼び出します。
そして、replaceOccurrencesメソッドの引数「of」に置換前の文字、引数「with」に置換後の文字を指定します。
let replace = str.replacingOccurrences(of: "x", with: "y") //xをyに置き換える
replaceOccurencesメソッドは、引数「of」に指定した文字を、引数「with」に指定した文字に置き換えた文字列を返します。
使用例
var str = "Heaao,Swift"
var replace = str.replacingOccurrences(of: "a", with: "l")
print(replace) // Hello,Swift
オススメの記事
コメント