Text between: Difference between revisions

Add Swift
m (fixed misspelling)
(Add Swift)
Line 2,446:
text_between("One fish two fish red fish blue fish", "fish ", " red") = "two fish"
text_between("FooBarBazFooBuxQuux", "Foo", "Foo") = "BarBaz"</pre>
 
=={{header|Swift}}==
 
<lang swift>import Foundation
 
let tests = [
("Hello Rosetta Code world", "Hello ", " world"),
("Hello Rosetta Code world", "start", " world"),
("Hello Rosetta Code world", "Hello ", "end"),
("</div><div style=\"chinese\">你好嗎</div>", "<div style=\"chinese\">", "</div>"),
("<text>Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">", "<text>", "<table>"),
("<table style=\"myTable\"><tr><td>hello world</td></tr></table>", "<table>", "</table>"),
("The quick brown fox jumps over the lazy other fox", "quick ", " fox"),
("One fish two fish red fish blue fish", "fish ", " red"),
("FooBarBazFooBuxQuux", "Foo", "Foo")
]
 
public extension String {
func textBetween(_ startDelim: String, and endDelim: String) -> String {
precondition(!startDelim.isEmpty && !endDelim.isEmpty)
 
let startIdx: String.Index
let endIdx: String.Index
 
if startDelim == "start" {
startIdx = startIndex
} else if let r = range(of: startDelim) {
startIdx = r.upperBound
} else {
return ""
}
 
if endDelim == "end" {
endIdx = endIndex
} else if let r = self[startIdx...].range(of: endDelim) {
endIdx = r.lowerBound
} else {
endIdx = endIndex
}
 
return String(self[startIdx..<endIdx])
}
}
 
for (input, start, end) in tests {
print("Input: \"\(input)\"")
print("Start delimiter: \"\(start)\"")
print("End delimiter: \"\(end)\"")
print("Text between: \"\(input.textBetween(start, and: end))\"\n")
}</lang>
 
{{out}}
 
<pre style="scroll: overflow; height: 20em">Input: "Hello Rosetta Code world"
Start delimiter: "Hello "
End delimiter: " world"
Text between: "Rosetta Code"
 
Input: "Hello Rosetta Code world"
Start delimiter: "start"
End delimiter: " world"
Text between: "Hello Rosetta Code"
 
Input: "Hello Rosetta Code world"
Start delimiter: "Hello "
End delimiter: "end"
Text between: "Rosetta Code world"
 
Input: "</div><div style="chinese">你好嗎</div>"
Start delimiter: "<div style="chinese">"
End delimiter: "</div>"
Text between: "你好嗎"
 
Input: "<text>Hello <span>Rosetta Code</span> world</text><table style="myTable">"
Start delimiter: "<text>"
End delimiter: "<table>"
Text between: "Hello <span>Rosetta Code</span> world</text><table style="myTable">"
 
Input: "<table style="myTable"><tr><td>hello world</td></tr></table>"
Start delimiter: "<table>"
End delimiter: "</table>"
Text between: ""
 
Input: "The quick brown fox jumps over the lazy other fox"
Start delimiter: "quick "
End delimiter: " fox"
Text between: "brown"
 
Input: "One fish two fish red fish blue fish"
Start delimiter: "fish "
End delimiter: " red"
Text between: "two fish"
 
Input: "FooBarBazFooBuxQuux"
Start delimiter: "Foo"
End delimiter: "Foo"
Text between: "BarBaz"</pre>
 
=={{header|UNIX Shell}}==