C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Method: 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.
Swift program that splits with components, separatedBy
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)
}
Output
3
["apple", "peach", "kiwi"]
apple
peach
kiwi
Method: 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.
ForSwift program that splits on multiple chars
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)
}
Output
["a", "b", "c", "d"]
a
b
c
d
Tip: This func handles different kinds of line separators, for UNIX and Windows. It is part of Foundation.
Swift program that uses enumerateLines
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)
}
Output
cat
dog
bird
Here: The "schools" array has two empty strings. We use isEmpty in filter to remove those. We print our results.
Swift program that splits, removes empty entries
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)
Output
["Harvard", "Princeton", "", "", "Yale"]
["Harvard", "Princeton", "Yale"]