可以通过以下步骤实现:
#import <Foundation/Foundation.h>
NSString *scoreString = @"The score is 90";
NSScanner *scanner = [NSScanner scannerWithString:scoreString];
[scanner setScanLocation:0];
int score;
if ([scanner scanInt:&score]) {
NSLog(@"Detected score: %d", score);
} else {
NSLog(@"Failed to detect score");
}
float score;
if ([scanner scanFloat:&score]) {
NSLog(@"Detected score: %.2f", score);
} else {
NSLog(@"Failed to detect score");
}
NSString *prefix;
NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"is"];
if ([scanner scanUpToCharactersFromSet:characterSet intoString:&prefix]) {
NSLog(@"Detected prefix: %@", prefix);
} else {
NSLog(@"Failed to detect prefix");
}
NSScanner是Foundation框架中的一个强大工具,可以用于字符串的解析和数据的提取。它可以根据指定的格式或字符集来扫描字符串,并将扫描到的数据转换为不同的数据类型。在Objective-C中,NSScanner常用于解析用户输入、文件读取、网络数据处理等场景。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云