1

我有一个已经从网站提取文本的文本视图。所以,假设文本视图中的文本有这个文本:

Save Location 

84°F 

Clear 

Feels like 90°F

在此文本中,如何将“84°F”中显示 84 的文本提取为字符串?请记住,84 是网站上不断变化的变量,因此有时它会是一个不同的数字,我无法直接搜索该数字。如果您知道如何执行此操作,请告诉我 :) 感谢您抽出宝贵时间。

4

1 回答 1

3

尝试这样的事情:

NSString *originalString = @"Save Location 84°F Clear Feels like 90°F";

NSMutableString *stringWithNums = [NSMutableString stringWithCapacity:originalString.length];

NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *numbers = [NSCharacterSet 
                       characterSetWithCharactersInString:@"0123456789"];

while ([scanner isAtEnd] == NO) {
    NSString *buffer;
    if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) {
        [stringWithNums appendString:buffer];

    } else {
        [scanner setScanLocation:([scanner scanLocation] + 1)];
        [stringWithNums appendString:@" "];
    }
}

现在stringWithNums将包含如下内容:

84(一些空格)90

然后你可以像这样解析stringWithNums

NSArray *tempArray = [stringWithNums componentsSeparatedByString: @" "];
NSString *finalTemperature;

for(int index = 0; index < [tempArray count]; index++){

    if([[tempArray objectAtIndex:index] intValue] != 0 && [[tempArray objectAtIndex:index] intValue] < 200){
        finalTemperature = [tempArray objectAtIndex: index];
        break;
    }
}

finalTemperature将包含“84”。您可以将其放在方法形式中并originalString作为参数传入,以便您可以重用此代码。希望这会有所帮助,如果您有任何问题,请务必在评论中提问!

更新:我添加了这一行: && [[tempArray objectAtIndex:index] intValue] < 200

到上面的 if 语句,所以它现在看起来像这样:

if([[tempArray objectAtIndex:index] intValue] != 0 && [[tempArray objectAtIndex:index] intValue] < 200){

在网站文本中,“82”之前的唯一数字似乎是邮政编码,长度为 5 位。实际上,所有温度(地球上)都低于 200(3 位数),所以我输入的额外行确保最终温度是三位数或更少的数字,而不是 5 位数的邮政编码。

希望这可以帮助!

于 2012-07-16T04:41:08.977 回答