【问题标题】:how i get an int from string?我如何从字符串中获取 int?
【发布时间】:2015-10-23 23:59:39
【问题描述】:

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

这是字符串:

大部分是干燥的。非常温和(周六下午最高 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()
    }

}

【问题讨论】:

    标签: ios string swift int


    【解决方案1】:

    使用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)")
    }
    

    【讨论】:

    • 祝你好运,当文本显示“68ºF”时。
    • @gasher729,在这种情况下有什么问题?它打印[68]
    • 我试图理解代码,但在这些部分有点困惑:“-?[0-9]{1,3}”,我可以在哪里找到逐行解释.. .
    • -?[0-9]{1,3} 表示查找可能以减号 (-?) 开头后跟 0 到 9 ([0-9]) 之间的 1 - 3 ({1,3}) 位数字的匹配项跨度>
    • 正则表达式的文档在这里:userguide.icu-project.org/strings/regexp
    猜你喜欢
    • 1970-01-01
    • 2020-02-12
    • 2011-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-16
    • 2011-06-30
    • 1970-01-01
    相关资源
    最近更新 更多