Swift 程式從給定字串中刪除字首子字串


要從給定字串中刪除字首子字串,首先我們使用內建的 hasPrefix() 函式檢查給定的子字串是否在指定的字串中。然後使用內建的 index() 函式查詢字首子字串的索引,最後刪除字首子字串。

輸入

String = “Today is cloudy day”
SubString = “Today”

輸出

“is cloudy day”

這裡,指定的子字串在給定字串中被找到,因此在結果字串中,我們從輸入字串的開頭刪除了子字串。

演算法

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

  • 步驟 2 − 建立一個子字串。

  • 步驟 3 − 檢查字串是否以指定的子字串開頭。

  • 步驟 4 − 如果是,則使用 index() 函式計算開始刪除的索引。這裡我們將字首子字串的計數作為偏移量傳遞。

  • 步驟 5 − 現在我們使用字串切片操作從給定索引到字串末尾提取一個子字串。之後使用 String() 函式將返回結果轉換為字串。

  • 步驟 6 − 列印輸出。

示例

在下面的 Swift 程式中,我們將從給定字串中刪除字首子字串。因此,建立一個字串和子字串。然後檢查指定的子字串是否在給定字串中。如果是,則使用 index() 函式查詢開始刪除的索引。然後使用字串切片操作從給定索引到字串末尾提取子字串,然後我們將使用 String() 初始化器和提取的子字串建立一個新字串。最後,我們將列印輸出。如果子字串不存在,則返回“字串未找到”。

import Foundation
import Glibc

let str = "Sky is blue" 
let prefixStr = "Sky" 

print("Original String:", str)

// Check if the string starts with the 
// prefix substring or not
if str.hasPrefix(prefixStr) {
   // Finding the index to start deleting from
   let SIndex = str.index(str.startIndex, offsetBy: prefixStr.count)
    
   // Removing the prefix substring
   let modifyStr = String(str[SIndex...])
    
   print("Modified String:", modifyStr)
} else {
    
   print("Substring not found")
}

輸出

Original String: Sky is blue
Modified String:  is blue

結論

所以這就是我們如何從給定字串中刪除字首子字串的方法。這是從輸入字串開頭刪除子字串最有效的方法。透過對程式碼進行一些小的更改,您也可以從字串開頭刪除字元。

更新於: 2023年5月9日

765 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告