@@ -142,3 +142,52 @@ extension String {
142142 return self . trimmingCharacters ( in: CharacterSet . whitespacesAndNewlines)
143143 }
144144}
145+
146+ // MARK: - Slicing using characters
147+
148+ extension String {
149+
150+ /// Returns a sliced string of given string
151+ /// from the first `start` character to the last `end` character.
152+ ///
153+ /// If the lower bound is greater than the upper bound, it returns an empty string.
154+ /// If the given string doesn't contain given characters, it also returns an empty string.
155+ ///
156+ /// - Parameters:
157+ /// - start: The character value being the lower bound of the given string.
158+ /// - end: The character value being the upper bound of the given string.
159+ /// - inversed: A boolean value that indicates whether the sliced string is inversed.
160+ /// The Default value is `false`.
161+ ///
162+ /// - Returns: A sliced string of given string.
163+ public func sliced( from start: Character , to end: Character , inversed: Bool = false ) -> String {
164+ guard let startCharacterIndex = firstIndex ( of: start) ,
165+ let endCharacterIndex = lastIndex ( of: end) ,
166+ startCharacterIndex <= endCharacterIndex
167+ else { return " " }
168+ let slicedSubstring = self [ startCharacterIndex ... endCharacterIndex]
169+ return !inversed ? String ( slicedSubstring) : String ( slicedSubstring. reversed ( ) )
170+ }
171+
172+ /// Slices a given string
173+ /// from the first `start` character to the last `end` character.
174+ ///
175+ /// If the lower bound is greater than the upper bound, it becomes an empty string.
176+ /// If the given string doesn't contain given characters, it also becomes an emtpy string.
177+ ///
178+ /// - Parameters:
179+ /// - start: The character value being the lower bound of the given string.
180+ /// - end: The character value being the upper bound of the given string.
181+ /// - inversed: A boolean value that indicates whether the sliced string is inversed.
182+ /// The Default value is `false`.
183+ public mutating func slice( from start: Character , to end: Character , inversed: Bool = false ) {
184+ guard let startCharacterIndex = firstIndex ( of: start) ,
185+ let endCharacterIndex = lastIndex ( of: end) ,
186+ startCharacterIndex <= endCharacterIndex else {
187+ self = " "
188+ return
189+ }
190+ let slicedSubstring = self [ startCharacterIndex ... endCharacterIndex]
191+ self = !inversed ? String ( slicedSubstring) : String ( slicedSubstring. reversed ( ) )
192+ }
193+ }
0 commit comments