Add version of replace method with limit.

Also rename parameters in original version.
This commit is contained in:
Kare Morstol
2014-11-06 00:04:51 +01:00
parent 4254364b74
commit cd5abf31d8
2 changed files with 38 additions and 3 deletions
+12 -3
View File
@@ -12,9 +12,18 @@
import Foundation
extension String {
public func replace (replaceOldString: String, _ withString: String) -> String {
return self.stringByReplacingOccurrencesOfString(replaceOldString, withString: withString)
public func replace (oldString: String, _ newString: String) -> String {
return self.stringByReplacingOccurrencesOfString(oldString, withString: newString)
}
/** Replace the first `limit` occurrences of oldString with newString. */
public func replace (oldString: String, _ newString: String, limit: Int) -> String {
let ranges = self.findAll(oldString) |> take(limit)
return ranges.count == 0
? self
: self.stringByReplacingOccurrencesOfString(oldString, withString: newString,
range: ranges.first!.startIndex ..< ranges.last!.endIndex)
}
public func split (sep: String) -> [String] {
+26
View File
@@ -34,4 +34,30 @@ class String_Tests: XCTestCase {
XCTAssertEqual(ranges("a ").count, 2)
}
func testReplaceStringwithstring () {
let text = "a b c aa bb cc ab bc ca"
XCTAssertEqual( text.replace("a", "x"), "x b c xx bb cc xb bc cx")
XCTAssertEqual( text.replace("b ", "x"), "a xc aa bxcc axbc ca")
}
func testReplaceOnlySomeStringsWithString () {
let text = "a b c aa bb cc ab bc ca"
XCTAssertEqual( text.replace("a", "x", limit: 0), "a b c aa bb cc ab bc ca")
XCTAssertEqual( text.replace("a", "x", limit: 2), "x b c xa bb cc ab bc ca")
XCTAssertEqual( text.replace("a", "x", limit: 4), "x b c xx bb cc xb bc ca")
XCTAssertEqual( text.replace("a", "x", limit: 5), "x b c xx bb cc xb bc cx")
XCTAssertEqual( text.replace("a", "x", limit: 6), "x b c xx bb cc xb bc cx")
XCTAssertEqual( text.replace("a", "[xy]", limit: 4), "[xy] b c [xy][xy] bb cc [xy]b bc ca")
XCTAssertEqual( text.replace("a", "[xy]", limit: 5), "[xy] b c [xy][xy] bb cc [xy]b bc c[xy]")
XCTAssertEqual( text.replace("a", "[xy]", limit: 6), "[xy] b c [xy][xy] bb cc [xy]b bc c[xy]")
XCTAssertEqual( text.replace("a ", "x", limit: 0), "a b c aa bb cc ab bc ca")
XCTAssertEqual( text.replace("a ", "x", limit: 1), "xb c aa bb cc ab bc ca")
XCTAssertEqual( text.replace("a ", "x", limit: 2), "xb c axbb cc ab bc ca")
XCTAssertEqual( text.replace("a ", "x", limit: 3), "xb c axbb cc ab bc ca")
}
}