Last active
October 29, 2021 12:59
-
-
Save ahcode0919/ac1e2edb3e6ade1d7ca742ae923e4383 to your computer and use it in GitHub Desktop.
A few ways to reverse a string in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let word = "abcdefg" | |
//Using swift lib | |
String(word.characters.reverse()) //"gfedcba" | |
//Using char array and insert | |
func reverseString(wordToReverse: String) -> String { | |
guard wordToReverse.characters.count > 1 else { | |
return wordToReverse | |
} | |
var reversedWord = [Character]() | |
for char in wordToReverse.characters { | |
reversedWord.insert(char, atIndex: 0) | |
} | |
return String(reversedWord) | |
} | |
assert(reverseString(word) == "gfedcba") | |
//Swap in-place, using char array | |
func reverseString2(wordToReverse: String) -> String { | |
guard wordToReverse.characters.count > 1 else { | |
return wordToReverse | |
} | |
var newWord = Array(wordToReverse.characters) | |
let maxIndex = newWord.count - 1 | |
for i in 0...maxIndex { | |
if i > maxIndex - i { | |
break | |
} | |
(newWord[i], newWord[maxIndex - i]) = (newWord[maxIndex - i], newWord[i]) | |
} | |
return String(newWord) | |
} | |
assert(reverseString2(word) == "gfedcba") |
@jmohanr here is what you look for: Time complexity: O(N), Space comp. : O(N)
func reverseWithSpaces(of str: String) -> String {
var newStr = [Character]()
var lastIndexOffset = str.count - 1
for char in str.enumerated() {
if char.element == " " {
newStr.insert(" ", at: 0)
} else {
let index = str.index(str.startIndex, offsetBy: lastIndexOffset)
newStr.insert(str[index], at: 0)
lastIndexOffset -= 1
}
}
return String(newStr)
}
// Test
let apple = "I am apple"
let reversedApple = reverseWithSpaces(of: apple)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hi I have one string like
let string = "I am apple"
I want to reverse the string like
let reverseString = "e lp pamai"
please can you help me