Last active
December 16, 2021 01:55
-
-
Save brennanMKE/5151a498c36d95a8440112facb172bad to your computer and use it in GitHub Desktop.
Character Surround Code Exercise
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
// 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