[英]Swift: Compare the first character of string
How can I compare the first character of a String against a character in Swift? 如何将字符串的第一个字符与Swift中的字符进行比较? For example:
例如:
Pseudo code: 伪代码:
str = "my name is John"
if str[0] == m {
}
let s = "abcd"
if s.hasPrefix("a") { // takes a String or a literal
}
if s.first == "a" { // takes a Character or a literal
}
if s[s.startIndex] == "a" { // takes a Character or a literal
}
This is for any charactor comparision in Swift 3 : 这适用于Swift 3中的任何字符比较:
var str: String = "abcd"
if str[str.index(str.startIndex, offsetBy: i)] == "a" {
}
where, i = use any index value of string In above example it is 0 i = 0 其中,i =使用string的任何索引值在上面的例子中,它是0 i = 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.