Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cut last characters of string and save it as variable in swift?

Tags:

string

swift

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
like image 993
Dylan Avatar asked Feb 01 '26 03:02

Dylan


1 Answers

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

A Generic Implementation

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:

  1. Extending a protocol instead of String to allow the function to be used with other types such as String.Subsequence.
  2. The use of @discardableResult which allows the function to be called to shorten the String without using the substring that is returned.
  3. Using a guard let statement to unwrap the optional return from range(of:) and provide an early exit if the range is nil.
  4. The use of defer to delay the removal of the substring until after the substring has been returned which avoids the use a local variable.
like image 154
vacawama Avatar answered Feb 03 '26 05:02

vacawama