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 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.