Swift – Check if String Starts with Another String
To check if a String str1
starts with another String str2
in Swift, use String.starts()
function. Call starts() function on str1
and pass str2
as argument.
The syntax to check if String str1
starts with the String str2
is
str1.starts(with: str2)
starts()
function returns a boolean value. If string str1
starts with the string str2
, then the function returns true
, else the function returns false
.
Example
In this example, we will take two string in variables str1 and str2. Using String.starts() function, we will check if the string str1 starts with the string str2.
main.swift
var str1 = "abcdefgh"
var str2 = "abcd"
var result = str1.starts(with: str2)
print( "Does str1 start with str2? \(result)" )
Output
Does str1 start with str2? true
Now, we will take different values for str1 and str2, such that str1 does not start with str2, and check the result of starts() function.
main.swift
var str1 = "abcdefgh"
var str2 = "ccd"
var result = str1.starts(with: str2)
print( "Does str1 start with str2? \(result)" )
Output
Does str1 start with str2? false
Conclusion
In this Swift Tutorial, we learned how to check if a string starts with another specific string using String.starts() function.