How can I compare the first character of a String against a character in Swift? For example:
Pseudo code:
str = "my name is John"
if str[0] == m {
}
To get the first character from a string, we can use the string. first property in swift.
In Swift, you can check for string and character equality with the "equal to" operator ( == ) and "not equal to" operator ( != ).
To get the first character of a string, we can call charAt() on the string, passing 0 as an argument. For example, str. charAt(0) returns the first character of str . The String charAt() returns the character of a string at the specified index.
Swift 2 String Search The contains() function has been replaced by the contains() method that can be invoked on the characters property of the new Swift 2 String. The find() function has been replaced with a new method called indexOf() that works on your characters property.
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With