From 95be58c0980bd35ad6a6ec0e4443b62b725b4f1b Mon Sep 17 00:00:00 2001 From: Yigit Yilmaz Date: Thu, 22 Aug 2019 02:21:06 +0300 Subject: [PATCH] improved solution for 1.3 --- .../Contents.swift | 34 ++++++------------- 1 file changed, 10 insertions(+), 24 deletions(-) diff --git a/Ch 1. Arrays and Strings/Ch 1. Arrays and Strings.playground/Pages/1.3 URLify.xcplaygroundpage/Contents.swift b/Ch 1. Arrays and Strings/Ch 1. Arrays and Strings.playground/Pages/1.3 URLify.xcplaygroundpage/Contents.swift index 989b49e..b7c4fe9 100644 --- a/Ch 1. Arrays and Strings/Ch 1. Arrays and Strings.playground/Pages/1.3 URLify.xcplaygroundpage/Contents.swift +++ b/Ch 1. Arrays and Strings/Ch 1. Arrays and Strings.playground/Pages/1.3 URLify.xcplaygroundpage/Contents.swift @@ -7,34 +7,20 @@ import Foundation extension String { - func urlIfy() -> String { - var s = "" - for char in self { - s += char == " " ? "%20" : String(char) - } - return s - } - - mutating func urlIfyInPlace() { - var replacements = 0 - for i in indices where self[i] == " " { - replaceSubrange(i...i, with: "%") - let next = index(after: i) - insert(contentsOf: "20", at: next) - replacements += 1 + func replaceSpaces(n: Int) -> String { + let charArray = Array(self)[0...n-1] + + let stringArray = charArray.map { (char) -> String in + return String(char) == " " ? "%20" : String(char) } - removeLast(replacements * 2) + + return stringArray.map({$0}).joined() } } let verify = "mr%20john%20smith" -var string = "mr john smith" -assert(string.urlIfy() == verify) - -string = "mr john smith " -var copy = string -copy.urlIfyInPlace() -print("\"\(copy)\"") -assert(copy == verify) +var string = "mr john smith " +assert(string.replaceSpaces(n: 13) == verify) +