Created
August 20, 2019 04:57
-
-
Save bradleyyin/77defc1c5bdeec97f4898360ee5b0d20 to your computer and use it in GitHub Desktop.
code challenge AH
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"Challenge 7: Condense whitespace | |
Difficulty: Easy | |
Write a function that returns a string with any consecutive spaces replaced with a single space. | |
Sample input and output | |
I've marked spaces using "[space]" below for visual purposes: | |
The string "a[space][space][space]b[space][space][space]c" should return "a[space]b[space]c". | |
The string "[space][space][space][space]a" should return "[space]a". | |
The string "abc" should return "abc"." | |
Excerpt From: Paul Hudson. "Swift Coding Challenges." Apple Books. | |
import Foundation | |
func condenseWhiteSpace(string: String) -> String { | |
var subStringArray: [String] = [] | |
let index = string.index(string.startIndex, offsetBy: 0) | |
if string[index] == " " { | |
subStringArray.append(" ") | |
} | |
let subStrings = string.split(separator: " ") | |
for subString in subStrings { | |
let subStringString = String(subString) | |
subStringString.replacingOccurrences(of: " ", with: "") | |
subStringArray.append(subStringString) | |
} | |
let indexEnd = string.index(string.endIndex, offsetBy: -1) | |
if string[indexEnd] == " " { | |
subStringArray.append(" ") | |
} | |
return subStringArray.joined(separator: " ") | |
} | |
condenseWhiteSpace(string: "a b c") | |
condenseWhiteSpace(string: " a") | |
condenseWhiteSpace(string: "abc") | |
condenseWhiteSpace(string: "a ") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment