HasPrefix
, hasSuffix
A string
's beginning or end can be tested in many ways. We could loop over characters. We could take a substring.
But for simplicity, we can use the hasPrefix
or hasSuffix
methods. These are "starts with" and "ends with" methods. They are easy to call and well-tested.
With the hasPrefix
and hasSuffix
funcs, we test the starts and ends of strings. These return true or false. They tell us whether the characters exist at the specified place.
if
-statement conditions evaluate to true. The inner 3 print statements are reached.var test = "one and two" // Test the string's prefix. if test.hasPrefix("one") { print(true) } // Test the suffix. if test.hasSuffix("two") { print(true) } // This prefix is not correct. // ... Use exclamation mark to test for this condition. if !test.hasPrefix("abc") { print(false) }true true false
To determine a string
does not start or end with another string
, we use the exclamation mark. This means "not." An "else if" can also be used.
Some languages require us to develop special methods for testing prefixes and suffixes. The Swift language does not. We use the built-in hasPrefix
and hasSuffix
.