hasSuffix()
方法用于检查字符串是否以指定字符串结尾。
示例
var str = "Kathmandu"
// checks if "Kathmandu" ends with "ndu"
print(str.hasSuffix("ndu"))
// Output: true
hasSuffix() 语法
字符串 hasSuffix()
方法的语法如下:
string.hasSuffix(str: String)
此处,string 是 String
类的一个对象。
hasSuffix() 参数
hasSuffix()
方法接受一个参数:
- str - 检查 string 是否以 str 结尾
hasSuffix() 返回值
hasSuffix()
方法返回:
- true - 如果字符串以给定的字符串结尾
- false - 如果字符串不是以给定的字符串结尾
注意:hasSuffix()
方法区分大小写。
示例 1:Swift 字符串 hasSuffix()
var str = "Swift Programming"
print(str.hasSuffix("ing")) // true
print(str.hasSuffix("g")) // true
print(str.hasSuffix("Programming")) // true
print(str.hasSuffix("programming")) // false
print(str.hasSuffix("min")) // false
输出
true true true false false
示例 2:使用 hasSuffix() 和 if...else
var song = "For the good times"
// true because song has "good times" suffix
if(song.hasSuffix("good times")) {
print ("Penned by Kris")
}
else {
print ("Some Other song ")
}
// false because song doesn't have "Good time" suffix
if(song.hasSuffix("For the")){
print ("Penned by Bernard")
}
else{
print ("Some other artist ")
}
输出
Penned by Kris Some other artist