2011-07-27 68 views
1

兩行字符串解析是:使用NSScanner解析字符串

00:02.0 VGA compatible controller [0300]: Intel Corporation 82945G/GZ Integrated Graphics Controller [8086:2772] (rev 02) 
00:02.1 Display controller [0380]: Intel Corporation 82945G/GZ Integrated Graphics Controller [8086:2776] (rev 02) 

讓這些字符串出來:

(從1號線)

  • VGA兼容控制器
  • 英特爾公司82945G/GZ集成圖形控制器
  • [8086:2772]

(來自第二行)

  • 顯示控制器
  • 英特爾公司82945G/GZ集成圖形控制器
  • [8086:2776]

現在我的起始碼是:

NSScanner *scn = [NSScanner scannerWithString:strtoparse]; 
NSString *devtype;  
while ([scn isAtEnd] == NO) 
    { 
     if([scn scanUpToCharactersFromSet:[NSCharacterSet whitespaceCharacterSet] intoString:NULL] && 
     [scn scanUpToString:@"[" intoString:&devtype]); 
    } 

和這不起作用。我甚至不能從文檔中理解掃描儀。那麼有人可以發佈工作代碼嗎?

回答

2

快速片段:

NSString *theString = @"00:02.0 VGA compatible controller [0300]: Intel Corporation 82945G/GZ Integrated Graphics Controller [8086:2772] (rev 02)\n00:02.1 Display controller [0380]: Intel Corporation 82945G/GZ Integrated Graphics Controller [8086:2776] (rev 02)"; 

NSScanner *theScanner = [NSScanner scannerWithString:theString]; 

NSCharacterSet *space = [NSCharacterSet characterSetWithCharactersInString:@" "]; 
NSCharacterSet *bracket = [NSCharacterSet characterSetWithCharactersInString:@"["]; 
NSCharacterSet *linebreak = [NSCharacterSet newlineCharacterSet]; 

NSString *type; 
NSString *name; 
NSString *number; 

while (![theScanner isAtEnd]) 
{ 
    [theScanner scanUpToCharactersFromSet:space intoString:nil] ; 
    [theScanner scanUpToCharactersFromSet:bracket intoString:&type]; 
    [theScanner scanUpToCharactersFromSet:space intoString:nil] ; 
    [theScanner scanUpToCharactersFromSet:bracket intoString:&name]; 
    [theScanner scanUpToCharactersFromSet:space intoString:&number]; 
    [theScanner scanUpToCharactersFromSet:linebreak intoString:nil] ; 

    NSLog(type); 
    NSLog(name); 
    NSLog(number); 
} 

輸出:

VGA compatible controller 
Intel Corporation 82945G/GZ Integrated Graphics Controller 
[8086:2772] 
Display controller 
Intel Corporation 82945G/GZ Integrated Graphics Controller 
[8086:2776]