Skip to content

Instantly share code, notes, and snippets.

@hernandazevedo
Created May 21, 2019 14:21
Show Gist options
  • Save hernandazevedo/2e6afb39972fcde19cbe298d6ddea767 to your computer and use it in GitHub Desktop.
Save hernandazevedo/2e6afb39972fcde19cbe298d6ddea767 to your computer and use it in GitHub Desktop.
import Foundation
func remove(input: String, first: Int, last: Int) -> String {
// we require a variable to manipulate strings
let newString = input
// modify newString and return the result
let firstIndex = newString.index(newString.startIndex, offsetBy: first)
let lastIndex = newString.index(newString.endIndex, offsetBy: (last * -1))
let firstSubstring = newString[..<firstIndex]
let lastSubstring = newString[lastIndex..<newString.endIndex]
return String(firstSubstring + lastSubstring)
}
func remove(input: String, first: Int, last: Int) -> String {
// we require a variable to manipulate strings
var newString = input
// modify newString and return the result
if first + last > newString.count {
return ""
}
var counter = first
var firstSubstring = ""
while counter > 0 {
firstSubstring += String(newString.removeFirst())
counter -= 1
}
counter = last
var lastSubstring = ""
while counter > 0 {
lastSubstring += String(newString.removeLast())
counter -= 1
}
return String(firstSubstring + lastSubstring.reversed())
}
print(remove(input: "Hello there world!", first: 5, last: 7))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment