Home > OS >  How to extract a negative number from a String?
How to extract a negative number from a String?

Time:07-22

I have a string with a math equation which can contain a negative number "-6-9".

I need to extract all numbers from this string and put them into a numbersArray:

let numbersArray = string.components(separatedBy: CharacterSet(charactersIn: " -x/"))

Output I need: ["-6", "9"]

Output I receive: ["", "6", ""]

I think it's because I have a string with doubled characters. In my case I have two minuses in the string (-) and with this minus I am trying to separate the string.

How can I separate the numbers in the string properly to receive a desired output?

CodePudding user response:

you just have separate first character check if it is a symbol

var string = "-6-9"
let number = "1234567890"
 
func seperateIfSymbolOnStart() -> (String?,String) {
        if let firstChar = string.first {
            if number.contains(firstChar) {
                return (nil,string)
            } else {
                // if first is not a number
                let first = "\(string.first!)"
                string.remove(at: string.startIndex)
                let withoutFirst = string
                return (first,withoutFirst)
            }
        }
        return (nil,"not found")
  }

there is symbol if any

let firstSymbol = seperateIfSymbolOnStart().0

and string without first symbol

let string = seperateIfSymbolOnStart().1

now you can do anything with symbol and string

CodePudding user response:

You can do that with regex, something like this will do:

 do {
        let string = "-6-9"
        let regex = try NSRegularExpression(pattern: "[\\ \\-][0-9] ")
        let results = regex.matches(in: string,
                                    range: NSRange(string.startIndex..., in: string))
        let res = results.map {
            String(string[Range($0.range, in: string)!])
        }
        print((res.compactMap { Int($0) })
    }
    catch {

    }

Output:

[-6, -9]
  • Related