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