Objective-C: Find numbers in string

前端 未结 7 1028
遇见更好的自我
遇见更好的自我 2020-11-27 04:37

I have a string that contains words as well as a number. How can I extract that number from the string?

NSString *str = @\"This is my string. #1234\";


        
相关标签:
7条回答
  • 2020-11-27 05:14

    Swift extension for getting number from string

    extension NSString {
    
    func getNumFromString() -> String? {
    
        var numberString: NSString?
        let thisScanner = NSScanner(string: self as String)
        let numbers = NSCharacterSet(charactersInString: "0123456789")
        thisScanner.scanUpToCharactersFromSet(numbers, intoString: nil)
        thisScanner.scanCharactersFromSet(numbers, intoString: &numberString)
        return numberString as? String;
    }
    }
    
    0 讨论(0)
提交回复
热议问题