Need to reverse strings without affecting characters which user can add by themself. For example i need to reverse abcd123 and ignore "b" and "3" so i need to get 2b1dca3. By ignoring i mean this characters should stay in place and do not swap with others. My code is working only with full word for example
func reverseWithoutFilter(FullText:String, TextToIgnore:String) -> String {
let fullTextArray = FullText.components(separatedBy: " ")
let textToIgnoreArray = TextToIgnore.components(separatedBy: " ")
let result = fullTextArray.map{!textToIgnoreArray.contains($0) ? String($0.reversed()) : $0}
return result.joined(separator: " ")
}
var result = reverseWithoutFilter(FullText: "FOX is good", TextToIgnore: "FOX")
// result will be "FOX si doog"
Second example
final class ExceptionRuleReverseManager {
var exceptionElements = String()
func reverse(string: String) -> String {
let words = string.components(separatedBy: " ")
var result = [String]()
for word in words {
result.append(rearrangeWord(word))
}
return String(result.joined(separator: " "))
}
private func rearrangeWord(_ word: String) -> String {
var arrayOfCharacters = Array(word)
if var firstElementIndex = arrayOfCharacters.indices.first,
var secondElementIndex = arrayOfCharacters.indices.last {
while firstElementIndex < secondElementIndex {
if isException(element: word[firstElementIndex]) {
// If first element is exception - skip it
firstElementIndex += 1
// If second element is exception - skip it
} else if isException(element: word[secondElementIndex]) {
secondElementIndex -= 1
} else {
// If both elements are not exceptions - swap them
arrayOfCharacters.swapAt(firstElementIndex, secondElementIndex)
firstElementIndex += 1
secondElementIndex -= 1
}
}
}
return String(arrayOfCharacters)
}
private func isException(element: String.Element) -> Bool {
return exceptionElements.contains(element)
}
}
extension String {
subscript (index: Int) -> String.Element {
let stringIndex = self.index(self.startIndex, offsetBy: index)
return self[stringIndex]
}
}
var ReverseManager = ExceptionRuleReverseManager()
ReverseManager.exceptionElements = "A2"
var input = "Alloha 234"
var result = ReverseManager.reverse(string: input)
print(result)
// result = Aaholl 243
ReverseManager.exceptionElements = "4B"
input = "Ball4 456"
result = ReverseManager.reverse(string: input)
// result = Blla4 465