Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Compare the first character of string

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 {
} 
like image 420
user2924482 Avatar asked Jun 30 '16 20:06

user2924482


People also ask

How do I find the first character of a string in Swift?

To get the first character from a string, we can use the string. first property in swift.

How do I compare characters in Swift?

In Swift, you can check for string and character equality with the "equal to" operator ( == ) and "not equal to" operator ( != ).

How do you get the first character of a string?

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.

How do I find a character in a string Swift?

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.


2 Answers

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
}
like image 160
Sulthan Avatar answered Sep 28 '22 11:09

Sulthan


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

like image 26
Nahush Sarje Avatar answered Sep 28 '22 11:09

Nahush Sarje