Swift 程式插入字串到另一個字串


Swift 提供了一個名為 insert() 的函式來將一個字串插入到另一個字串中。insert(at:) 函式在指定位置的當前字串中新增一個新字元或字串。

輸入

String = “Program to learn”
New String = “Swift”

輸出

String = Swift Program to learn”

這裡我們在輸入字串的索引 1 處插入一個新的字串。所以我們在輸出中得到“Swift Program to learn”。

語法

func insert(newVal, at: idx)

其中 newVal 表示我們要插入到給定字串中的新字串,idx 是我們將 newVal 插入到現有字串中的有效索引。

演算法

  • 步驟 1 − 建立一個字串。

  • 步驟 2 − 建立另一個字串,我們將將其插入到給定字串中。

  • 步驟 3 − 使用 index() 函式查詢我們將插入新字串的索引值。

  • 步驟 4 − 現在使用 insert() 函式將新字串插入到給定字串中。

  • 步驟 5 − 列印輸出。

示例

在下面的 Swift 程式中,我們將一個字串插入到另一個字串中。要執行此任務,我們將建立兩個原始字串和新字串。原始字串是我們將在其中插入新字串的主字串。然後,我們計算使用 index() 將插入新字串的索引值,然後使用 insert() 函式,我們將新字串插入到指定索引處的原始字串中。

import Foundation
import Glibc

var originalStr = "my blue car"
let newStr = "color "

print("Original String:", originalStr)

// Finding index
let idx = originalStr.index(originalStr.startIndex, offsetBy: 3)

// Inserting new string in the current string
originalStr.insert(contentsOf: newStr, at: idx)

print("Updated String:", originalStr)

輸出

Original String: my blue car
Updated String: my color blue car

結論

這就是我們如何將一個字串插入到另一個字串中的方法。使用 insert() 函式,您可以在指定字串的任何索引處插入任何字串或字元。但請記住,索引必須是有效索引。如果您插入任何無效語法,則此方法將丟擲異常。

更新於: 2023年5月9日

684 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.