Skip to content

Instantly share code, notes, and snippets.

@brennanMKE
Last active December 16, 2021 01:55
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 brennanMKE/5151a498c36d95a8440112facb172bad to your computer and use it in GitHub Desktop.
Save brennanMKE/5151a498c36d95a8440112facb172bad to your computer and use it in GitHub Desktop.
Character Surround Code Exercise
// Tweet: https://twitter.com/christianselig/status/1471197660111593473?s=12
let input = "|||||"
// option 1 - works but is not generic to be reused with other characters
input.replacingOccurrences(of: "|", with: "n|") + "n"
// option 2 - this function is more flexible and allows input to have any characters
func surround(input: String, spacer: String) -> String {
input.isEmpty ? input : input.map { "\(spacer)\($0)" }.joined() + spacer
}
surround(input: input, spacer: "n")
// an empty string is handled with a ternary operator with a single line
surround(input: "", spacer: "n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment