2013-03-04 180 views
0

我遇到componentsSeparatedByString:問題,它給了我奇怪的結果。componentsSeparatedByString:不會拆分包含分隔符中所有字符的字符串

有了這個代碼:

CCLOG(@" Found string %@",string); 
tokens = [string componentsSeparatedByString:@"[,]"]; 

CCLOG(@" sanity %@", (NSString *)[tokens objectAtIndex:0]); 
int type = [(NSString *)[tokens objectAtIndex:0] integerValue]; 
int x = [(NSString *)[tokens objectAtIndex:1] integerValue]; //<< breakpoint 

我得到這個輸出日誌:

2013-03-03 21:29:39.184 Legends[33427:c07]  Found string 1[0,5] 
2013-03-03 21:29:39.185 Legends[33427:c07]  sanity 1[0,5] 

所以它是有道理的,因爲在陣令牌的第一個對象的最後一行的程序中斷了整個字符串,但不應將字符串@"1[0,5]"分割成@"1"@"0"@"5"

回答

2

不,你誤解了該方法的工作原理。 componentsSeparatedByString:不使用傳遞字符串中的單個字符,而是使用整個字符串。您的分隔符是三個字符的序列[,]。像@"pecan[,]pie"這樣的字符串使用此分隔符,但@"1[0,5]"沒有。類似的方法componentsSeparatedByCharactersInSet:會做你期待什麼:

[string componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"[,]"]]; 

如果你想拉出的數字串,並得到他們的數值,你可能想看看NSScanner