How to perform reversing of all words in a sentence.
Example
let str = \"Hello playground\"
Result should be like \"olleH dnuorg
Building on the OPs answer, if you wanted to follow English capitalization rules on the output:
var str = "Hello playground"
let result = str.split(separator: " ").enumerated().map {
let reversed = String($0.1.reversed())
return $0.0 == 0 ? reversed.capitalized : reversed.lowercased()
}
.joined(separator: " ")
print("Rerversing letters in each word = \"" + result + "\"") // Olleh dnuorgyalp
Also note that multiple spaces would mess this up, as would commas, periods, and other word/sentence delimiters.
Working code!
import UIKit
var str = "Hello playground"
let result = str.split(separator: " ").map { String($0.reversed())}.joined(separator: " ")
print(result) // olleH dnuorgyalp
let result = String(str.reversed())
.components(separatedBy: .whitespaces)
.reversed()
.joined(separator: " ")
You can use String
method enumerateSubstrings
using .byWords
options and replace the subrange of each word with the substring reversed. Note that this way the punctuation will remain in place:
import Foundation
Mutating approach:
var str = "Hello, playground!!!"
str.enumerateSubstrings(in: str.startIndex..., options: .byWords) { _, range, _, _ in
str.replaceSubrange(range, with: str[range].reversed())
}
print(str) // "olleH, dnuorgyalp!!!"
Non mutating:
let str = "Hello, playground!!!"
var result = ""
str.enumerateSubstrings(in: str.startIndex..., options: .byWords) { string, range, enclosingRange, _ in
result.append(contentsOf: string!.reversed())
result.append(contentsOf: str[range.upperBound..<enclosingRange.upperBound])
}
print(result) // "olleH, dnuorgyalp!!!"
Here's the typical functional programming approach (also posted by @Saranjith)
let result = str
.components(separatedBy: " ")
.map { $0.reversed() }
.joined()
First of all lets define
n
: the number of characters in the input stringk
: the number of words in the input string (of course k<=n) Now lets look at the time complexity of each piece of our code
.components(separatedBy: " ")
This instructions need to go through the entire string so O(n)
.map { $0.reversed() }
Here each word is reversed. So if we have k
words we have a time complexity of
O(m0) + O(m1) + ... + O(mk-1)
where mi
is the length of the i-th
word.
However the sum of the length of all the words is <= n so we can say that
O(m0) + O(m1) + ... + O(mk-1) <= O(n)
.joined()
Finally we have k
words which need to be joined togheter. This can be done in O(k)
that, again, is <= O(n)
.
Wrap up
let result = str
.components(separatedBy: " ") // O(n)
.map { $0.reversed() } // O(m0) + O(m1) + ... + O(mk-1) <= O(n)
.joined() // O(k) <= O(n)
Time complexity = O(n) + O(n) + O(n) = O(n)