1

I have some Strings that vary in length but always end in "listing(number)"

myString = 9AMnep8MAziUCK7VwKF51mXZ2listing28

.

I want to get the String without "listing(number)":

9AMnep8MAziUCK7VwKF51mXZ2

.

Methods I've tried such as .index(of: ) only let you format based off one character. Any simple solutions?

August Kimo
  • 1,503
  • 8
  • 17
  • 2
    What about using a regex: `let regex = try! NSRegularExpression.init(pattern: "(.*?)(listing\\d+)", options: []); let newStr = regex.stringByReplacingMatches(in: str, options: [], range: NSRange(location: 0, length: str.utf16.count), withTemplate: "$1")`? – Larme Jun 09 '20 at 15:27
  • Yeah, regex is what I was going to suggest too. – matt Jun 09 '20 at 15:27
  • Is there possibility that there would be more than one `listing` in the initial string? – user28434'mstep Jun 10 '20 at 09:26
  • Yes, there is a answer that works with any number after "listing" – August Kimo Jun 11 '20 at 14:15

3 Answers3

2

A possible solution is to search for the substring with Regular Expression and remove the result (replace it with empty string)

let myString = "9AMnep8MAziUCK7VwKF51mXZ2listing28"
let trimmedString = myString.replacingOccurrences(of: "listing\\d+$", with: "", options: .regularExpression)
  • \\d+ searches for one ore more digits
  • $ represents the end of the string

Alternatively without creating a new string

var myString = "9AMnep8MAziUCK7VwKF51mXZ2listing28"
if let range = myString.range(of: "listing\\d+$", options: .regularExpression) {
    myString.removeSubrange(range)
}
vadian
  • 274,689
  • 30
  • 353
  • 361
1

Another option is to split the string in parts with "listing" as separator

let result = myString.components(separatedBy: "listing").first
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
-1

So to solve your issue find the code below with few comments written to try and explain each steps have taken. kindly note i have modified or arrived at this solution using this links as a guide.

  1. https://stackoverflow.com/a/40070835/6596443
  2. https://www.dotnetperls.com/substring-swift

    extension String {
        //
        // Paramter  inputString: This is the string you want to manipulate
        // Paramter- startStringOfUnwanted: This is the string you want to start the removal or replacement from
        //return : The expected output you want but can be emptystring if unable to
    
        static func trimUnWantedEndingString(inputString: String,startStringOfUnwanted: String) -> String{
            //Output string
            var outputString: String?
            //Getting the range based on the string content
            if let range = myString.range(of: startStringOfUnwanted) {
                //Get the lowerbound of the range
                let lower = range.lowerBound
                //Get the upperbound of the range
                let upper = range.upperBound
                //Get the integer position of the start index of the unwanted string i added plus one to ensure it starts from the right position
                let startPos = Int(myString.distance(from: myString.startIndex, to: lower))+1
                //Get the integer position of the end index of the unwanted string i added plus one to ensure it starts from the right position
                let endPos =  Int(myString.distance(from: myString.startIndex, to: upper))+1
                //Substract the start int from the end int to get the integer value that will be used to get the last string i want to stop trimming at
                let endOffsetBy = endPos-startPos
                //get thes string char ranges of values
                let result = myString.index(myString.startIndex, offsetBy: 0)..<myString.index(myString.endIndex, offsetBy: -endOffsetBy)
                //converts the results to string or get the string representation of the result and then assign it to the OutputString
                outputString = String(myString[result]);
            }
            return outputString ?? "";
        }
    }
    let myString = "9AMnep8MAziUCK7VwKF51mXZ2listing28"
    String.trimUnWantedEndingString(inputString: myString, startStringOfUnwanted:"listing")