Multisplit: Difference between revisions

Add Swift
(Add Swift)
Line 1,936:
["a", "!=", "", "==", "b", "=", "", "!=", "c"]
</pre>
 
=={{header|Swift}}==
 
Swift strings are purposefully not index by integers to avoid confusion and performance traps when dealing with unicode. As such the indexes returned by this method are not very helpful to a human reader, but can be used to manipulate the original string.
 
{{trans|Python}}
 
<lang swift>extension String {
func multiSplit(on seps: [String]) -> ([Substring], [(String, (start: String.Index, end: String.Index))]) {
var matches = [Substring]()
var matched = [(String, (String.Index, String.Index))]()
var i = startIndex
var lastMatch = startIndex
 
main: while i != endIndex {
for sep in seps where self[i...].hasPrefix(sep) {
if i > lastMatch {
matches.append(self[lastMatch..<i])
} else {
matches.append("")
}
 
lastMatch = index(i, offsetBy: sep.count)
matched.append((sep, (i, lastMatch)))
i = lastMatch
 
continue main
}
 
i = index(i, offsetBy: 1)
}
 
if i > lastMatch {
matches.append(self[lastMatch..<i])
}
 
return (matches, matched)
}
}
 
let (matches, matchedSeps) = "a!===b=!=c".multiSplit(on: ["==", "!=", "="])
 
print(matches, matchedSeps.map({ $0.0 }))</lang>
 
 
{{out}}
 
<pre>["a", "", "b", "", "c"] ["!=", "==", "=", "!="]</pre>
 
=={{header|Tcl}}==