次のようなものを試してください。
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桁の郵便番号ではなく3桁以下になるようになります。
お役に立てれば!