我有一个NSString,其中包含以下字符串:
"Model Name: Mac mini
Model Identifier: Macmini6,1
Processor Name: Intel Core i5
Processor Speed: 2.5 GHz
Number of Processors: 1
Total Number of Cores: 2
L2 Cache (per Core): 256 KB
L3 Cache: 3 MB
Memory: 4 GB
Boot ROM Version: MM61.0106.B03
SMC Version (system): 2.7f1
Serial Number (system): C07M81SWDWYL
Hardware UUID: 3B2564A0-7F96-5774-9C93-E56769E9344D"
我想将有关处理器名称和型号名称的信息检索到另一个nsstring中。怎么做。
答案 0 :(得分:1)
不理想,快速且肮脏且依赖于字符串格式的解决方案:
-(NSString*) getValueFromString:(NSString *)text forTag:(NSString*)tag withNextTag:(NSString*)nextTag
{
NSRange tagRange = [text rangeOfString:[tag stringByAppendingString:@": "]];
NSRange nextTagRange = [text rangeOfString:[nextTag stringByAppendingString:@":"]];
NSUInteger start = tagRange.location + tagRange.length;
NSUInteger length = nextTagRange.location - start - 1; //-1 to skip a space before the next tag name
return [text substringWithRange:NSMakeRange(start, length)];
}
用法:
NSString *input = @"Model Name: Mac mini Model Identifier: Macmini6,1 Processor Name: Intel Core i5 Processor Speed: 2.5 GHz Number of Processors: 1 Total Number of Cores: 2 L2 Cache (per Core): 256 KB L3 Cache: 3 MB Memory: 4 GB Boot ROM Version: MM61.0106.B03 SMC Version (system): 2.7f1 Serial Number (system): C07M81SWDWYL Hardware UUID: 3B2564A0-7F96-5774-9C93-E56769E9344D";
NSLog(@"test: %@", [self getValueFromString:input forTag:@"Processor Name" withNextTag:@"Speed"]);
此外,您可以尝试查找有关正则表达式的信息。
答案 1 :(得分:1)
这又是一个依赖于字符串格式的解决方案,并假设每一行用" \ n"分隔。
NSString *string = @"Model Name: Mac mini\nModel Identifier: Macmini6,1\nProcessor Name: Intel Core i5\nProcessor Speed: 2.5 GHz\nNumber of Processors:1\nTotal Number of Cores:2\nL2 Cache (per Core): 256 KB\nL3 Cache: 3 MB\nMemory: 4 GB\nBoot ROM Version: MM61.0106.B03\nSMC Version (system): 2.7f1\nSerial Number (system): C07M81SWDWYL\nHardware UUID: 3B2564A0-7F96-5774-9C93-E56769E9344D";
NSArray *array = [string componentsSeparatedByString:@"\n"];
NSMutableDictionary *dict = [NSMutableDictionary new];
for (NSString *string in array) {
NSString *key = [string componentsSeparatedByString:@":"][0];
NSString *value = [string componentsSeparatedByString:@":"][1];
[dict setObject:value forKey:key];
}
NSLog(@"Model Name : %@", dict[@"Model Name"]);
NSLog(@"Processor Name : %@", dict[@"Processor Name"]);