I have a string of test@me
now I want to create a code that let me cut where the @ is and save it as a variable, so the expected result is string1 = test string2 = @me
a code will be something like this
func test(string: String) {
var mString = string
var cuttedString = mString.cutFrom("@")
print(mString)
print(cuttedString)
}
test(string: "test@me")
result:
test
@me
Here is an extension of String which performs the function you desire. It takes a String and mutates the calling String by removing everything from that part on, and it returns the part that was removed.
import Foundation
extension String {
mutating func cut(from string: String) -> String {
if let range = self.range(of: string) {
let cutPart = String(self[range.lowerBound...])
self.removeSubrange(range.lowerBound...)
return cutPart
}
else {
return ""
}
}
}
func test(string: String) {
var mString = string
let cutString = mString.cut(from: "@")
print(mString)
print(cutString)
}
test(string: "test@me")
test @me
Here is a generic implementation suggested by @LeoDabus in the comments:
extension StringProtocol where Self: RangeReplaceableCollection {
@discardableResult mutating func removeSubrange<S: StringProtocol>(from string: S) -> SubSequence {
guard let range = range(of: string) else { return "" }
defer { removeSubrange(range.lowerBound...) }
return self[range.lowerBound...]
}
}
It nicely demonstrates:
String to allow the function to be used with other types such as String.Subsequence.@discardableResult which allows the function to be called to shorten the String without using the substring that is returned.guard let statement to unwrap the optional return from range(of:) and provide an early exit if the range is nil.defer to delay the removal of the substring until after the substring has been returned which avoids the use a local variable.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With