我在下面有这个NSString。我希望能够获取每个应用程序的名称及其位置。有人可以帮助我或指出我正确的方向吗? 提前谢谢。
Applications:
Xcode:
Version: 4.5.2
Last Modified: 11/3/12 11:45 PM
Kind: Intel
64-Bit (Intel): Yes
App Store: Yes
Location: /Applications/Xcode.app
Terminal:
Version: 2.3
Last Modified: 6/21/12 12:01 AM
Kind: Intel
64-Bit (Intel): Yes
App Store: No
Location: /Applications/Utilities/Terminal.app
Google Chrome:
Version: 23.0.1271.64
Last Modified: 10/31/12 7:59 PM
Kind: Intel
64-Bit (Intel): No
App Store: No
Location: /Applications/Google Chrome.app
App Store:
Version: 1.2.1
Last Modified: 4/18/12 7:52 PM
Kind: Intel
64-Bit (Intel): Yes
App Store: No
Location: /Applications/App Store.app
答案 0 :(得分:1)
使用您的字符串创建NSScanner的实例。由于NSScanner的实例默认默认跳过空格和换行符,因此您需要在继续操作之前禁用此行为,如下所示:
[scanner setCharactersToBeSkipped:[[[NSCharacterSet alloc] init] autorelease]];
从这里开始,你会做这样的事情:
NSString *appName = nil;
[scanner scanString:@"Applications:" intoString:NULL];
NSCharacterSet *charset = [NSCharacterSet newlineCharacterSet];
[scanner scanCharactersFromSet:charset intoString:NULL];
while ([scanner isAtEnd] == NO)
{
// Get your application name.
[scanner scanUpToCharactersFromSet:charset intoString:&appName];
[scanner scanCharactersFromSet:charset intoString:NULL];
// You could do something with your application name here.
// Skip over the other stuff.
for (NSUInteger idx = 0; idx < 6; idx++)
{
[scanner scanUpToString:@":" intoString:NULL];
[scanner scanString:@":" intoString:NULL];
[scanner scanUpToCharactersFromSet:charset intoString:NULL];
[scanner scanCharactersFromSet:charset intoString:NULL];
}
}
请注意,尽管有外表,但我没有给你一个完整的解决方案。除了检查字符串的结尾之外,没有错误检查,并且不用说Real Applications检查错误。 (甚至应该在一开始就检查字符串结尾。)此外,此代码段依赖于数据的严格表示,例如您提供的。
答案 1 :(得分:0)
如果有简单的分隔符,我会使用componentsSeparatedByString。如果没有,请尝试使用带有NSRegularExpression的正则表达式来查找值
答案 2 :(得分:0)
有很多方法可以解决这个问题。已提及NSRegularExpression
。 NSScanner
是另一个。这是一个潜在的解决方案(不保证正确性 - 只是一个指南。)
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSString *source = @"Applications:\n\nXcode:\n\n Version: 4.5.\n Last Modified: 11/3/12 11:45 PM\n Kind: Intel\n 64-Bit (Intel): Yes\n App Store: Yes\n Location: /Applications/Xcode.app";
NSScanner *scanner = [NSScanner scannerWithString:source];
[scanner scanUpToString:@":" intoString:NULL];
[scanner scanString:@":" intoString:NULL];
while( ![scanner isAtEnd] ) {
NSString *appName = nil;
NSString *appPath = nil;
[scanner scanUpToCharactersFromSet:[NSCharacterSet alphanumericCharacterSet] intoString:NULL];
[scanner scanCharactersFromSet:[NSCharacterSet alphanumericCharacterSet] intoString:&appName];
NSString *junk = nil;
[scanner scanUpToString:@"Location: " intoString:&junk];
[scanner scanString:@"Location: " intoString:NULL];
[scanner scanUpToString:@"\n" intoString:&appPath];
[scanner scanString:@"\n" intoString:NULL];
printf("app name = %s, path = %s\n",[appName UTF8String],[appPath UTF8String]);
}
}
return 0;
}