Home
Swift
String hasPrefix and hasSuffix Examples
This page was last reviewed on Aug 22, 2023.
Dot Net Perls
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.
if
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
Home
Changes
© 2007-2024 Sam Allen.