Skip to content

Instantly share code, notes, and snippets.

@dogweather
Last active August 30, 2022 06:19
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 dogweather/cf20f95d8579e2206890ec22dbf481f6 to your computer and use it in GitHub Desktop.
Save dogweather/cf20f95d8579e2206890ec22dbf481f6 to your computer and use it in GitHub Desktop.
Swift implementation of five string operations
func cleanUp(s: String) -> String {
return splitIntoSentences(summary: fixHyphenation(s: fixWhitespace(s: s)))[0]
}
func fixHyphenation(s: String) -> String {
return s.replacingOccurrences(of: "- ", with: "")
}
func fixWhitespace(s: String) -> String {
return s.replacingOccurrences(of: "\n", with: " ")
}
func splitIntoSentences(summary: String) -> [String] {
return summary
.components(separatedBy: ". ")
.map { ensureEndsWithPeriod(sentence: $0) }
}
func ensureEndsWithPeriod(sentence: String) -> String {
if let lastCharacter = sentence.characters.last {
if lastCharacter == "." {
return sentence
} else {
return sentence + "."
}
} else {
return sentence
}
}
import XCTest
class Tests: XCTestCase {
func testFixHyphenation() {
XCTAssertEqual( fixHyphenation(s: "auto- mobile"), "automobile" )
}
func testFixWhitespace() {
XCTAssertEqual( fixWhitespace(s: "and\nthe story"), "and the story" )
}
func testCleanUp() {
let input = "Relating to the state transient lodging tax; creating\nnew provisions; amending ORS 284.131 and\n320.305; prescribing an effective date; and pro-\nviding for revenue raising that requires approval\nby a three-fifths majority.\nWhereas Enrolled House Bill 2267 (chapter 818,"
let expected_output = "Relating to the state transient lodging tax; creating new provisions; amending ORS 284.131 and 320.305; prescribing an effective date; and providing for revenue raising that requires approval by a three-fifths majority."
XCTAssertEqual( cleanUp(s: input), expected_output )
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment