Skip to content

Instantly share code, notes, and snippets.

@bradleyyin
Created August 20, 2019 04:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradleyyin/77defc1c5bdeec97f4898360ee5b0d20 to your computer and use it in GitHub Desktop.
Save bradleyyin/77defc1c5bdeec97f4898360ee5b0d20 to your computer and use it in GitHub Desktop.
code challenge AH
"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