「Swift5」Stringクラスのindexメソッドで文字を挿入するサンプル

環境
# swift –version
Swift version 5.5.2 (swift-5.5.2-RELEASE)
Target: x86_64-unknown-linux-gnu

書式
var 変数名 = 対象文字列の値
let インデックス値 =変数名.index(変数名.startIndex, offsetBy: 値)
変数名.insert(contentsOf: 挿入文字列, at: インデックス値)

使用例

var res = "studyskill"
print("文字を挿入する前")
print(res)

let idx = res.index(res.startIndex, offsetBy: 4)
res.insert(contentsOf: "arkgame", at: idx) 
print("文字を挿入する後")
print(res)

実行結果
文字を挿入する前
studyskill
文字を挿入する後
studarkgameyskill

Swift

Posted by arkgame