Swift 程式:刪除給定字串的字尾子串
要刪除給定字串的字尾子串,首先我們使用內建的 `hasSuffix()` 函式檢查給定的子串是否存在於指定的字串中。然後使用內建的 `index()` 函式查詢字尾子串的索引,最後刪除字尾子串。
輸入
String = “Siya love cooking” Substring = “cooking”
輸出
“Siya love”
在這裡,指定的子串在給定字串中被找到,因此在結果字串中,我們從輸入字串的末尾刪除了該子串。
演算法
步驟 1 − 建立一個字串。
步驟 2 − 建立一個子串。
步驟 3 − 檢查字串是否以指定的子串結尾。
步驟 4 − 如果是,則使用 `index()` 函式計算停止刪除的索引。這裡我們傳遞字尾子串的負數計數作為偏移量,以指示停止刪除的位置。
步驟 5 − 現在我們使用字串切片操作從輸入字串中提取子串,但不包括指定的索引。並使用 `String()` 函式將返回的結果轉換為字串。
步驟 6 − 列印輸出。
示例
在下面的 Swift 程式中,我們將從給定字串中刪除字尾子串。因此,建立一個字串和子串。然後檢查指定的子串是否存在於給定字串中。如果是,則在 `index()` 函式的幫助下找到停止刪除的索引。然後使用字串切片提取從輸入字串開始但不包括指定索引的子串,然後我們將使用 `String()` 初始化器建立一個包含提取子串的新字串。最後,我們將列印輸出。如果子串不存在,則返回“字串未找到”。
import Foundation import Glibc let str = "Sky is blue" let suffixStr = " blue" print("Original String:", str) // Checking if the string ends with the // suffix substring or not if str.hasSuffix(suffixStr) { // Find the index to stop deleting at let LIndex = str.index(str.endIndex, offsetBy: -suffixStr.count) // Removing the suffix substring let modifyStr = String(str[..<LIndex]) print("Modified String:", modifyStr) } else { print("String not found") }
輸出
Original String: Sky is blue Modified String: Sky is
結論
這就是我們如何從給定字串中刪除字尾子串的方法。這是從輸入字串末尾刪除子串的最有效方法。透過對程式碼進行一些小的更改,您還可以從字串末尾刪除字元。
廣告