是否有可能在objective-c框架内识别NSString中特定char的位置和存在?例如,如果我有NSString @“hello”并且我想知道char“e”的位置和存在,我怎么能这样做?
答案 0 :(得分:2)
在字符串中搜索单个字符有一种特殊的方法,但您只需搜索长度为1的子字符串范围并请求返回范围的位置,如下所示:
NSRange charRange = [@"hello" rangeOfString:@"e"];
NSUInteger index = charRange.location;
if (index == NSNotFound) {
NSLog(@"substring not found");
}
您可以在此处找到完整的文档:rangeOfString:
要查找@"e"
中所有@"hello"
的索引,您可能需要执行以下操作:
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".
文档:NSMutableIndexSet,NSIndexSet
修改:将 @bbum 中的算法替换为对此答案的评论中描述的算法。
答案 1 :(得分:0)
查看NSString的Apple文档。
- (NSRange)rangeOfString:(NSString *)aString