简体   繁体   中英

How to get value from point(a b) swift

I have this kind of string: " POINT(101.650577657408 3.1653186153213) ".

Anyone know how can I get the first and second value of POINT from this String?

You can easily spit the string using componentsSeparatedByString function.

let myStr = "POINT(101.650577657408 3.1653186153213)"
let characterSet = NSCharacterSet(charactersInString: "( )")
var splitString = myStr.componentsSeparatedByCharactersInSet(characterSet)
print(splitString[0])
print(splitString[1])
print(splitString[2])

The above only works if you have the complete one String.

Although the NSCharacterSet solution is correct but here is another solution using the most powerful regex .

var error: NSError?

// Initialise the regex for a float value
let regex: NSRegularExpression = NSRegularExpression(pattern: "(\\d*\\.\\d*)", options: NSRegularExpressionOptions.CaseInsensitive, error: &error)! 

// Matches array contains all the match found for float in given string
let matches: NSArray = regex.matchesInString(str as String, options: NSMatchingOptions.ReportProgress, range: NSMakeRange(0, str.length))

// You can easily get all values by enumeration
for match in matches {
    println(str.substringWithRange(match.range))
}

The benefit of this solution is it will scan all the float values and will also work in case of pattern got changed.

Try this, this will work for your string

    let myStr = "POINT(101.650577657408 3.1653186153213)"
    let strWithout_POINT_openingBrace = myStr.stringByReplacingOccurrencesOfString("POINT(", withString: "")//"101.650577657408 3.1653186153213)"
    let strWithout_closingBrace = strWithout_POINT_openingBrace.stringByReplacingOccurrencesOfString(")", withString: "")//"101.650577657408 3.1653186153213"
    //now you have only space between two values
    //so split string by space
    let arrStringValues = strWithout_closingBrace.componentsSeparatedByString(" ");//["101.650577657408","3.1653186153213"]

    print(arrStringValues[0]);//first value "101.650577657408"
    print(arrStringValues[1]);//second value "3.1653186153213"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM