Swift 程式檢查字串是否以指定子字串結尾


Swift 提供了一個 hasSuffix() 函式來檢查字串是否以指定的子字串結尾。hasSuffix() 函式返回一個布林值,指示指定的子字串是否與輸入字串的結尾字元匹配。hasSuffix() 函式區分大小寫,這意味著根據此函式,“t”和“T”是兩個不同的值。

輸入

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

輸出

yes

這裡,子字串的字元與輸入字串的結尾字元匹配。

語法

func hasSuffix(value)

這裡,value 表示一個字串。如果 value 與輸入字串的結尾字元匹配,則此函式返回 true。否則,它將返回 false。如果 value 是空字串,它也會返回 false。

演算法

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

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

  • 步驟 3 - 使用 hasSuffix() 函式確定給定字串是否以子字串結尾。

  • 步驟 4 - 列印輸出。

示例 1

在以下 Swift 程式中,我們將檢查一個以指定子字串結尾的字串。因此,建立一個字串和兩個子字串。然後使用 hasSuffix() 函式確定輸入字串是否以子字串結尾。如果輸入字串以子字串結尾,則 hasSuffix() 函式將返回 true。否則,它將返回 false。

import Foundation
import Glibc

let myStr = "Car color is green" 
let suffixStr1 = "green" 
let suffixStr2 = "blue"

// Checking whether the string ends with the 
// suffix substring or not
var res1 = myStr.hasSuffix(suffixStr1)
var res2 = myStr.hasSuffix(suffixStr2)

print("Is '\(myStr)'ends with the substring'\(suffixStr1)'?:", res1)
print("Is '\(myStr)'ends with the substring'\(suffixStr2)'?:", res2)

輸出

Is 'Car color is green'ends with the substring'green'?: true
Is 'Car color is green'ends with the substring'blue'?: false

示例 2

在以下 Swift 程式中,我們將檢查一個以指定子字串結尾的字串。因此,建立一個字串和一個子字串。然後使用 hasSuffix() 函式確定輸入字串是否以子字串結尾。如果輸入字串以子字串結尾,則列印“YES!給定字串以指定的子字串結尾。”。否則,列印“NO!給定字串沒有以指定的子字串結尾。”

import Foundation
import Glibc

let myStr = "Learn Swift programming" 
let suffixStr = "programming" 

// Checking if the string ends with the 
// suffix substring or not
if myStr.hasSuffix(suffixStr) {
   print("YES! the given string ends with the specified substring.")
} else {
   print("NO! the given string does not end with the specified substring.")
}

輸出

YES! the given string ends with the specified substring.

結論

因此,這就是我們如何使用 hasSuffix() 函式檢查字串是否以指定的子字串結尾。此方法將子字串的每個字元與輸入或給定字串的結尾字元進行比較。如果任何字元與給定字串不匹配,則此函式將返回 false。

更新於: 2023-05-09

720 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告