2011-04-19 37 views
0

是否可以在objective-c框架內標識NSString中特定字符的位置和存在?例如,如果我有NSString @「hello」,並且想知道char「e」的位置和存在,我將如何能夠做到這一點?讀取NSString中的每個字符

回答

2

有一個字符串中查找單個字符特定的方法,但你可以只搜索長度爲1的子串的範圍,並要求返回的範圍內的位置,因爲這樣的:

NSRange charRange = [@"hello" rangeOfString:@"e"]; 
NSUInteger index = charRange.location; 
if (index == NSNotFound) { 
    NSLog(@"substring not found"); 
} 

你可以在這裏找到完整文檔:rangeOfString:

要找到你可能想要做這樣的事情在@"hello"所有@"e"的指標,雖然:

NSString *haystack = @"hellol"; 
NSString *needle = @"l"; 
NSMutableIndexSet *indices = [NSMutableIndexSet indexSet]; 
NSUInteger haystackLength = [haystack length]; 
NSRange range = NSMakeRange(0, haystackLength); 
NSRange searchRange = range; 
while (range.location != NSNotFound) { 
    range = [haystack rangeOfString:needle options:0 range:searchRange]; 
    if (range.location != NSNotFound) { 
     [indices addIndex:range.location]; 
     NSUInteger searchLocation = range.location + 1; 
     NSUInteger searchLength = haystackLength - searchLocation; 
     if (searchLocation >= haystackLength) { 
      break; 
     } 
     searchRange = NSMakeRange(searchLocation, searchLength); 
    } 
} 
//indices now holds the indices of all occurrences of 'e' in "hello". 

文檔:NSMutableIndexSetNSIndexSet

編輯:替換算法從在他的評論中所描述的這個答案@bbum的一個。

+0

...如果沒有'e',你會得到'NSNotFound'的位置。 – Tommy 2011-04-19 21:34:24

+0

是的,只是在你評論時加入到我的回答中。 ;) – Regexident 2011-04-19 21:36:42

+0

如果我改爲messaged:'[@「hello」rangeOfString:@「l」]''會返回'index' – locoboy 2011-04-19 21:47:15

0

看看蘋果文檔NSString

- (NSRange)rangeOfString:(NSString *)aString