remove parts of a string and return the removed parts - Swift

Asked

Viewed 387 times

0

How do I remove parts of a string and return those parts removed to another string on Swift?

Example:

var myString = "10setembro2017"
let newString = myString.removeAndReturn(index:1..2)

print(myString) //setembro2017
print(newString) //10

1 answer

1


This is much more complex than it looks, but I will try to explain in detail the step by step.

First you need to change the type of your function parameter to ... which in this case is called CountableClosedRange<Int> but String in Swift does not use Int as an index and yes String.Index.

To convert Int to index you need to use a method from String called index(String.Index, offsetBy: Int). To convert the start of your Voce subrange you need to pass the startIndex of his String and the lowerBound of its range as offset.

Remember that indices on Swift start at zero and not at one.

To convert the upperBound of its range in the endIndex of its subrange you can offset the lowerBound not to offset the lowerBound unnecessarily and pass the Count property of your range (which is equal to the difference of the upperBound except the lowerBound).

Then you save the substring from yours String in an Object that can be declared as constant and uses the removeSubrange method to remove the subrange from its String (Voce needs to declare the method as mutating in order to change its String).

Finished this is you only return a new String initialized with the substring you saved before removing the subrange.

And to top it off @discardableResult let you use this method and decart the result.

Xcode 10.2 • Swift 5

extension StringProtocol where Self: RangeReplaceableCollection {
    @discardableResult
    mutating func remove(range: ClosedRange<Int>) -> SubSequence {
        let lowerBound = index(startIndex, offsetBy: range.lowerBound)
        let upperBound = index(lowerBound, offsetBy: range.count)
        let subrange = lowerBound..<upperBound
        defer { removeSubrange(subrange) }
        return self[subrange]
    }
}

var string = "10setembro2017"
let range = 0...1
if string.count > range.upperBound {
    let dia = string.remove(range: range)
    print(dia) // "10\n"
    print(string)  // "setembro2017\n"
}
  • If you want to study a little more as subscript a String using Int I recommend looking at this answer that I posted on the site in English https://stackoverflow.com/questions/24092884/get-nth-character-of-a-string-in-Swift-Programming-language/38215613?s=1|43.0409#38215613 and also looks at the response that a friend of mine from Sweden called dfri posted yesterday. https://stackoverflow.com/a/46941709/2303865

  • Very good answer. What do you think of adding a note saying that the method will generate a crash if a crease negative and/or larger than the string size?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.