String Split Example (components)
This page was last reviewed on Aug 16, 2023.
Dot Net Perls
Split. A string has multiple parts separated by special characters (delimiter characters). We can separate these parts into a String array.
In Swift, there is no special split method. But we invoke components(), part of the Foundation library, with a separatedBy argument. This works well for splitting strings.
Initial example. Let us begin by splitting apart a string containing tasty fruits. The string contains apple, peach and kiwi, separated by commas.
Detail We invoke components() on the input string. We specify the separatedBy argument name. We pass a delimiter string.
Result A String array containing 3 strings is returned. Its count is 3, and we loop over and print the string data.
import Foundation // An example string separated by commas. let line = "apple,peach,kiwi" // Use components() to split the string. // ... Split on comma chars. let parts = line.components(separatedBy: ",") // Result has 3 strings. print(parts.count) print(parts) // Loop over string array. for part in parts { print(part) }
3 ["apple", "peach", "kiwi"] apple peach kiwi
Multiple chars. Sometimes a string contains many delimiter chars, not just one. For example this string has a colon, comma and semicolon for delimiters.
Detail The components() charactersIn method handles this case. We must pass it a CharacterSet.
Note A CharacterSet can be constructed with an init method that receives a string. Each character in the string is added to the set.
Result The four letters (single-character strings) are added to the result array. We loop over and display them.
import Foundation // This line has three different separators. let line = "a:b,c;d" // Create a CharacterSet of delimiters. let separators = CharacterSet(charactersIn: ":,;") // Split based on characters. let parts = line.components(separatedBy: separators) // Print result array. print(parts) // Loop over strings that were split apart. for part in parts { print(part) }
["a", "b", "c", "d"] a b c d
EnumerateLines. Often we just want to loop over lines in a string. With enumerateLines, we do not get a string array. We pass a closure to process each line in the string.
Tip This func handles different kinds of line separators, for UNIX and Windows. It is part of Foundation.
import Foundation // This string contains three lines. let source = "cat\ndog\r\nbird" // Enumerate lines in the string. source.enumerateLines { (line, stop) -> () in print(line) }
cat dog bird
Remove empty entries. Sometimes we get an empty string when we separate a string into an array. With filter, we can eliminate empty strings.
Here The "schools" array has two empty strings. We use isEmpty in filter to remove those. We print our results.
import Foundation // This string contains some empty sections. let data = "Harvard; Princeton; ; ; Yale"; // Split on the delimiter. let schools = data.components(separatedBy: "; ") // Use filter to eliminate empty strings. let nonempty = schools.filter { (x) -> Bool in !x.isEmpty } // Print before and after results. print(schools) print(nonempty)
["Harvard", "Princeton", "", "", "Yale"] ["Harvard", "Princeton", "Yale"]
Joined. In Swift we use the joined method to combine strings in a string array together. Join is the opposite of components(). We often use them together.
A note, Swift 3. For Swift 3, we use components() with a separatedBy argument instead of componentsSeparatedByString. This syntax is easier to read and type.
To summarize: Swift offers no string split() method. Instead we use the Foundation method that separates strings. Components() just splits strings based on the arguments.
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.
© 2007-2024 Sam Allen.