TheDeveloperBlog.com

Home | Contact Us

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

<< Back to SWIFT

Swift Trim Strings

Use Foundation to trim strings. Trim many characters in a set from the start and end of strings.
Trim. Often strings contain whitespace (like spaces or newlines) at their starts or ends. These characters are often removed or trimmed.
In Foundation, we locate a useful method called stringByTrimmingCharactersInSet. A character set is required. The result is a string with the specified characters removed.
An example. Let us begin with a simple example. We introduce a "source" string that contains a leading space, and a trailing period and space.

NSCharacterSet: We create a NSCharacterSet with three characters—a space, period, and a question mark.

Next: We invoke the trim method, stringByTrimmingCharactersInSet. We pass the set instance as an argument.

Result: The string returned has no leading or trailing spaces (and no period). The endIndex values indicate 3 characters were removed.

Swift program that trims string import Foundation // The string we are trimming. let source = " Areopagitica, John Milton. " // Create a character set of chars to trim. let set = NSCharacterSet(charactersInString: " .?") // Call func with character set. let result = source.stringByTrimmingCharactersInSet(set) // Write the result. print(result) // Print before and after lengths. print(source.endIndex) print(result.endIndex) Output Areopagitica, John Milton 28 25
An alternative. A custom pair of loops (for startIndex and endIndex) could be written. In these, we continue towards the center of a string as removable characters are encountered.

Then: We take a substring (of the inner part of the string) to perform the trimming operation.

Substring
A review. In Swift, strings are manipulated in many ways. With convenient methods like stringByTrimmingCharactersInSet, we avoid writing complex logic to eliminate characters.
© 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