Swift 程式移除字串中最後一個指定字元


要移除字串中最後一個指定的字元,Swift 提供了一個預定義的 remove(at:) 函式。此函式從指定位置或索引移除字元。

輸入

String = “Today is cloudy day”
Character = “o”

輸出

“Today is cludy day”

在輸入字串中字元“o”出現了兩次,因此使用 remove(at:) 函式我們移除了字串中“o”字元的最後一次出現。因此輸出字串為“Today is cludy day”。

語法

Str.remove(at:Idx)

其中 Str 是輸入字串,idx 是要移除的指定字元的有效位置/索引。

演算法

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

  • 步驟 2 − 建立一個字元型別的變數,並存儲要移除其最後出現的字元。

  • 步驟 3 − 現在檢查指定的字元是否出現在輸入字串中。

  • 步驟 4 − 如果是,則使用 lastIndex() 函式查詢指定字元的最後一個索引。

  • 步驟 5 − 然後使用 remove() 函式從輸入字串中移除指定字元的最後一次出現,並將結果儲存在一個新字串中。

  • 步驟 6 − 列印修改後的字串。

  • 步驟 7 − 如果未找到指定的字元,則列印“字元未找到”。

示例

在下面的 Swift 程式中,我們將從字串中移除最後一個指定的字元。所以首先建立一個字串和一個我們想要移除的字元。然後檢查指定的字元是否出現在輸入字串中。如果是,我們將找到指定字元最後一次出現的索引,然後使用 remove() 函式從字串中移除該字元,最後顯示更新後的字串。

import Foundation
import Glibc

let sentence = "Tutorials Point" 
let char: Character = "t" 

print("Original String:", sentence)

// Finding the last index of the character to remove
if let lIndex = sentence.lastIndex(of: char) {
   // Remove the character at the last index
   var modifyStr = sentence
   modifyStr.remove(at: lIndex)
    
   print("Modified String:", modifyStr)
} else {
   // Character not found in the string
   print("Character not found. Try Again")
}

輸出

Original String: Tutorials Point
Modified String: Tutorials Poin

結論

因此,這就是我們如何從字串中移除最後一個指定字元的方法。使用 remove() 方法,您還可以從字串中移除任何字元,但為此,您需要指定該字元的索引。如果索引不是有效索引,則此方法將丟擲異常。

更新於: 2023年5月10日

362 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.