0

In Swift I have a string like:

let str = "5~895893799,,6~898593679,,7~895893679,,8~895893799,,5~895893799,,6~898593679,,7~895893679,,8~895893799";

From this I need to get only the number which is before "~" which is [5,6,7,8,5,6,7,8]

How can I achieve this?

2
  • actual string is "5~895893799,,6~898593679,,7~895893679,,8~895893799,,5~895893799,,6~898593679,,7~895893679,,8~895893799" Commented Jul 20, 2019 at 22:14
  • 3
    Please post a snippet of code which is your best guess to solve this problem and ask for help to improve it. Commented Jul 20, 2019 at 22:42

2 Answers 2

3

Make use of components(separatedBy:) and compactMap.

let str = "5~895893799,,6~898593679,,7~895893679,,8~895893799,,5~895893799,,6~898593679,,7~895893679,,8~895893799"
let nums = str.components(separatedBy: ",,")
              .compactMap { $0.components(separatedBy: "~").first }

That gives the string array:

["5", "6", "7", "8", "5", "6", "7", "8"]

If you want an array of Int, add:

.compactMap { Int($0) }

to the end.

let nums = str.components(separatedBy: ",,")
              .compactMap { $0.components(separatedBy: "~").first }
              .compactMap { Int($0) }

That gives:

[5, 6, 7, 8, 5, 6, 7, 8]

Sign up to request clarification or add additional context in comments.

Comments

0

You could define this regular expression:

let regex = try! NSRegularExpression(pattern: #"\d+(?=~)"#)
  • \d : matches any digit
  • + : this is the one or more quantifier
  • (?=~) : Positive lookahead for "~"

and use it like so:

let range = NSRange(location: 0, length: (str as NSString).length)
let matches = regex.matches(in: str, range: range)

let strings: [String] = matches.map { match in
    let subRange = match.range
    let startIndex = str.index(str.startIndex, offsetBy: subRange.lowerBound)
    let endIndex = str.index(str.startIndex, offsetBy: subRange.upperBound)
    let subString = String(str[startIndex..<endIndex])

    return subString
}

let numbers = strings.compactMap(Int.init)  //[5, 6, 7, 8, 5, 6, 7, 8]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.