我如何从字符串中获取int?

时间:2015-08-01 10:31:23

标签: ios string swift int

正在开发一个天气应用程序,我想根据字符串中的度数生成图像,所以如何从字符串中提取数字

这是字符串:

  

大部分干燥。非常温和(周六下午最高19ºC,周日最低15ºC)。风一般都很轻。

 @IBAction func weatherButton(sender: UIButton) {

    let url = NSURL(string: "http://www.weather-forecast.com/locations/" + cityNameTextField.text.stringByReplacingOccurrencesOfString(" ", withString: "-") + "/forecasts/latest")

    if url != nil {

        let task = NSURLSession.sharedSession().dataTaskWithURL(url!){ (data, response, error) in

            var urlError = false
            var weather = ""


            if error == nil {

                var urlContent = NSString(data: data, encoding: NSUTF8StringEncoding)
                var urlContentArray = urlContent!.componentsSeparatedByString("<span class=\"phrase\">")

                if urlContentArray.count > 0 {

                    var weatherArray = urlContentArray[1].componentsSeparatedByString("</span>")
                    weather = weatherArray[0] as! String
                    weather = weather.stringByReplacingOccurrencesOfString("&deg;", withString: "º")
                    println(weather)

                }
                else {
                    urlError = true
                }
            }
            else {
                urlError = true
            }

            dispatch_async(dispatch_get_main_queue()) {
                if urlError == true {
                    self.showError()
                }
                else {
                    self.weatherFact.text = weather
                }
            }



        }
        task.resume()


    }
    else {
        showError()
    }

}

1 个答案:

答案 0 :(得分:2)

使用NSRegularExpression的另一种解决方案。 结果是Array个数字,正则表达式也考虑温度低于零

Swift 1.2

let string = "Mostly dry. Very mild (max -19ºC on Sat afternoon, min 15ºC on Sunnight). Wind will be generally light."
let regex = NSRegularExpression(pattern: "-?[0-9]{1,3}", options: NSRegularExpressionOptions(), error: nil)
if let matches = regex?.matchesInString(string, options: NSMatchingOptions(), range: NSRange(location:0, length:count(string))) {
    let degrees = matches.map {return (string as NSString).substringWithRange($0.range).toInt()! }
    println(degrees) // -> [-19, 15]
}

Swift 2.0

let string = "Mostly dry. Very mild (max -19ºC on Sat afternoon, min 15ºC on Sunnight). Wind will be generally light."
do {
    let regex = try NSRegularExpression(pattern: "-?[0-9]{1,3}", options: NSRegularExpressionOptions())
    let matches = regex.matchesInString(string, options: NSMatchingOptions(), range: NSRange(location: 0, length: string.characters.count))
    let degrees = matches.map {Int((string as NSString).substringWithRange($0.range))!}
    print(degrees) // -> [-19, 15]
}
catch {
    print("NSRegularExpression threw error: \(error)")
}