How to get number in NSString(with both numbers and characters)?

给你一囗甜甜゛ 提交于 2019-12-25 01:18:43

问题


I fetch the data from site into NSString like this:

        <td><font color=#ffffff>35</td>
        <td><font color=#ffffff>0</td>
        <td><font color=#ffffff>0</td>
        <td><font color=#ffffff>0</td>
        <td><font color=#ffffff>1</td>
        <td><font color=#ffffff>2</td>
        <td><font color=#ffffff>0</td>
        <td><font color=#ffffff>1</td>
        <td><font color=#ffffff>16</td>
        <td><font color=#ffffff>45.2</td>
        <td><font color=#ffffff>3.153</td>

and I want to convert into NSArray with numbers only.

I have been tried many classed and methods.. floatValue, componentsSeparatedByString, substringWithRange, .. all look like terrible and inefficient. Is there any basic method to solve this problem?

Thanks!


回答1:


The best general way to solve this is by using regular expressions. The regular expression

-?[0-9]*\.?[0-9]*

matches an optional negative sign, followed by some digits, followed by an optional decimal point, optionally followed by some more digits. Take a look at http://www.regular-expressions.info/floatingpoint.html for a nice discussion on how to best match numbers with a regular expression. The regex I give here is simpler than any shown on that page, but it's somewhat less robust.

To match regular expressions in Objective-C, you can use an NSRegularExpression. It has a function called enumerateMatchesInString that will call a code block every time it gets a match within a string. Here's an example of how you could use that to build up an array of NSNumbers:

NSString *str = @"<td><font color=#ffffff>35</td>\
<td><font color=#ffffff>0</td>\
<td><font color=#ffffff>0</td>\
<td><font color=#ffffff>0</td>\
<td><font color=#ffffff>1</td>\
<td><font color=#ffffff>2</td>\
<td><font color=#ffffff>0</td>\
<td><font color=#ffffff>1</td>\
<td><font color=#ffffff>16</td>\
<td><font color=#ffffff>45.2</td>\
<td><font color=#ffffff>3.153</td>";
NSMutableArray *numbers = [NSMutableArray new];
NSNumberFormatter *formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"-?[0-9]*\\.?[0-9]*" options:NSRegularExpressionAllowCommentsAndWhitespace error:nil];
[regex enumerateMatchesInString:str options:0 range:NSMakeRange(0, [str length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
    NSString *substr = [str substringWithRange:[match range]];
    NSNumber *number = [formatter numberFromString:substr];
    if (number) {
        [numbers addObject:number];
    }
}];
NSLog(@"ARRAY: %@", numbers);


来源:https://stackoverflow.com/questions/11989187/how-to-get-number-in-nsstringwith-both-numbers-and-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!