TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to SWIFT

Swift hasPrefix and hasSuffix Examples

Use the hasPrefix and hasSuffix methods to test the starts and ends of a string.
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.

Swift program that uses hasPrefix, hasSuffix 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) } Output 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.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf