William Hu
William Hu

Reputation: 16151

swift how to split string but contains the separators

I have a string like 100 + 8 - 9 + 10, how to get ["100", "+", "8", "-", "9", "+", "10"] in an array.

let string = "100 + 8 - 9 + 10"
let splitted = string.split(omittingEmptySubsequences: true, whereSeparator: { ["+", "-"].contains(String($0)) })

But I got ["100", "8", "9", "10"], I lost + and -, any good way? Thanks!

EDIT Thanks for the comment, not guarantee about spaces. Could be like "100+8 - 9 ".

Upvotes: 2

Views: 244

Answers (2)

Ashley Mills
Ashley Mills

Reputation: 53101

If you don't know whether or not the string will contain spaces, you should probably use a Scanner

let string = "100 + 8 - 9 + 10"

let removed = string.replacingOccurrences(of: " ", with: "")
// "100+8-9+10"

let scanner = Scanner(string: removed)

let operators = CharacterSet(charactersIn: "+-*/")

var components: [String] = []

while !scanner.isAtEnd {
    var value: Int = 0
    if scanner.scanInt(&value) {
        components.append("\(value)")
    }

    var op: NSString? = ""
    if scanner.scanCharacters(from: operators, into: &op) {
        components.append(op! as String)
    }
}

print(components)

// ["100", "+", "8", "-", "9", "+", "10"]

Upvotes: 2

Papershine
Papershine

Reputation: 5223

You can just split your string by spaces.

let splitted = string.split(separator: " ")

The value of splitted is

["100", "+", "8", "-", "9", "+", "10"]

Upvotes: 3

Related Questions