Objective c 从NSstring获取信息

Objective c 从NSstring获取信息,objective-c,Objective C,我有一个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 G

我有一个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中。如何做到这一点。

非最佳、快速、肮脏且依赖字符串格式的解决方案:

-(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"]);

此外,您还可以尝试查找有关正则表达式的信息。

这也是一种依赖于字符串格式的解决方案,并且假设每一行都由“\n”分隔


真的不可能以更简单、更可预测的格式获取此信息吗?我不知道怎么做,也没有尝试过..解析未指定格式的字符串并不简单,没有人会为您编写代码。做一些研究,写一些代码,然后问一个更好的问题。我想,你可以尝试阅读正则表达式。使用正则表达式是解析字符串的一种选择。如果格式不变,可能会起作用。不过我不相信它。在我看来,这个问题的“正确”答案是以不需要字符串解析的方式获取信息。[[uuu NSArrayI objectAtIndex:]:索引1超出界限[0..0]为我的字符串或您的输入字符串生成错误?
 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"]);