Objective c 读取NSString中的每个字符

Objective c 读取NSString中的每个字符,objective-c,nsstring,Objective C,Nsstring,是否可以在objective-c框架内识别NSString中特定字符的位置和存在?例如,如果我有NSString@“hello”,并且我想知道字符“e”的位置和存在,我将如何做到这一点?有特定的方法搜索字符串中的单个字符,但您可以只搜索长度为1的子字符串的范围并请求返回范围的位置,例如: NSRange charRange = [@"hello" rangeOfString:@"e"]; NSUInteger index = charRange.location; if (index == NS

是否可以在objective-c框架内识别NSString中特定字符的位置和存在?例如,如果我有NSString@“hello”,并且我想知道字符“e”的位置和存在,我将如何做到这一点?

有特定的方法搜索字符串中的单个字符,但您可以只搜索长度为1的子字符串的范围并请求返回范围的位置,例如:

NSRange charRange = [@"hello" rangeOfString:@"e"];
NSUInteger index = charRange.location;
if (index == NSNotFound) {
    NSLog(@"substring not found");
}
您可以在此处找到完整的文档:

要在
@“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".
文件:


编辑:将算法替换为@bbum中的算法,如他对此答案的评论所述。

请查看苹果文档


... 如果没有“e”,你会得到一个“NSNotFound”的位置。是的,当你评论时,我只是把它添加到我的答案中如果我改为发消息:
[@“hello”rangeOfString:@“l”]
,那么
索引将返回到
2
(匹配的第一次出现)。或者使用
rangeOfString:options:range:
并传递超出第一次出现的范围。累积结果,直到点击
NSNotFound
- (NSRange)rangeOfString:(NSString *)aString