diff --git a/README.md b/README.md index 65e15ae..2501c32 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,8 @@ These following methods are available for working with and manipulating `String` - [`after`](https://github.com/rkukuh/Swift-StringHelper#after) - [`before`](https://github.com/rkukuh/Swift-StringHelper#before) +- [`between`](https://github.com/rkukuh/Swift-StringHelper#between) +- [`camel case`](https://github.com/rkukuh/Swift-StringHelper#camel-case) ## Usage @@ -55,3 +57,25 @@ let result = originalString.before("@") print(result) // john ``` + +### `between` + +The `before` helper returns the portion of a string between two values. + +```swift +let originalString = "john@apple.com" +let result = originalString.between("john@", and: ".com") + +print(result) // Optional("apple") +``` + +### `camel case` + +The `camelCased` helper converts the given string to camelCaseLikeThis. + +```swift +var originalString = "Everyone CAN Code" +var result = originalString.camelCased() + +print(result) // everyoneCanCode +``` diff --git a/Sources/SwiftStringHelper/StringCamelCaseExtensions.swift b/Sources/SwiftStringHelper/StringCamelCaseExtensions.swift new file mode 100644 index 0000000..572cf97 --- /dev/null +++ b/Sources/SwiftStringHelper/StringCamelCaseExtensions.swift @@ -0,0 +1,19 @@ +// +// File.swift +// +// +// Created by R. Kukuh on 27/03/23. +// + +import Foundation + +public extension String { + func camelCased() -> String { + let words = self.components(separatedBy: CharacterSet.alphanumerics.inverted).filter { !$0.isEmpty } + + let firstWord = words.first?.lowercased() ?? "" + let remainingWords = words.dropFirst().map { $0.capitalized } + + return ([firstWord] + remainingWords).joined() + } +} diff --git a/Tests/SwiftStringHelperTests/StringCamelCasedTests.swift b/Tests/SwiftStringHelperTests/StringCamelCasedTests.swift new file mode 100644 index 0000000..03a48fe --- /dev/null +++ b/Tests/SwiftStringHelperTests/StringCamelCasedTests.swift @@ -0,0 +1,31 @@ +// +// StringCamelCasedTests.swift +// +// +// Created by R. Kukuh on 27/03/23. +// + +import XCTest +@testable import SwiftStringHelper + +class StringCamelCasedTests: XCTestCase { + + func testCamelCased() { + let originalString = "hello_world" + let result = originalString.camelCased() + XCTAssertEqual(result, "helloWorld", "The camel-cased string should be 'helloWorld'") + } + + func testCamelCasedWithMultipleSeparators() { + let originalString = "hello-world_example@text" + let result = originalString.camelCased() + XCTAssertEqual(result, "helloWorldExampleText", "The camel-cased string should be 'helloWorldExampleText'") + } + + func testCamelCasedWhenEmpty() { + let originalString = "" + let result = originalString.camelCased() + XCTAssertEqual(result, "", "The camel-cased string should be an empty string when the original string is empty") + } + +}