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.
An example. 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.
Here All 3 of the 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
Negation. 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.
A summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.