开发者

Reading each char in a NSString

开发者 https://www.devze.com 2023-02-26 21:05 出处:网络
Is it possible to identify the location and presence of a specific c开发者_JAVA百科har in a NSString within the objective-c framework? For example, if I have the NSString @\"hello\" and I wanted to kn

Is it possible to identify the location and presence of a specific c开发者_JAVA百科har in a NSString within the objective-c framework? For example, if I have the NSString @"hello" and I wanted to know the location and presence of the char "e", how would I be able to do this?


There is particular method for searching for single characters within a string, but you can just search for the range of a substring of length 1 and request the returned range's location, as such:

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

You can find full documentation here: rangeOfString:

To find the indices of all @"e" in @"hello" you might want to do something like this, though:

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".

Documentation: NSMutableIndexSet, NSIndexSet

Edit: Replaced algorithm with the one from @bbum's as described in his comment to this answer.


Take a look at the Apple Docs for NSString.

- (NSRange)rangeOfString:(NSString *)aString
0

精彩评论

暂无评论...
验证码 换一张
取 消