Objective-C: Find numbers in string

2019-01-05 01:30发布

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";

I would like to be able to strip out 1234 as an int. The string will have different numbers and words each time I search it.

Ideas?

7条回答
不美不萌又怎样
2楼-- · 2019-01-05 02:12

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;
}
}
查看更多
登录 后发表回答