有没有办法实现JAVA函数 int indexOf(int ch,int fromIndex)。
让我解释一下:
NSString *steSample = @"This is sample test string";
现在我希望获得 i 的索引,但是在第二个索引之后。我怎样才能做到这一点。
提前致谢
答案 0 :(得分:2)
正则表达式对我来说太复杂了:)
我们不能修剪它然后找它吗?
那是3行...
包装在一个类别中:
#import <Foundation/Foundation.h>
@interface NSString (Extend)
-(NSUInteger)indexOfSubstring:(NSString*)needle afterIndex:(NSUInteger)index;
@end
@implementation NSString (Extend)
-(NSUInteger)indexOfSubstring:(NSString*)needle afterIndex:(NSUInteger)index {
id str = [self substringFromIndex:index];
NSUInteger i = [str rangeOfString:needle].location;
return i==NSNotFound ? i : i+index;
}
@end
演示用法:
int main(int argc, char *argv[]) {
@autoreleasepool {
id str = @"@asd@asd";
NSUInteger index = [str indexOfSubstring:@"@" afterIndex:2];
NSLog(@"index of @ is: %d", index);
}
}
答案 1 :(得分:1)
我会做这样的事情:
NSString *_sample = @"This is sample test string";
NSError *_error;
NSRegularExpression *_regExp = [NSRegularExpression regularExpressionWithPattern:@"i" options:NSRegularExpressionCaseInsensitive error:&_error];
NSArray *_matches = [_regExp matchesInString:_sample options:NSMatchingReportCompletion range:NSMakeRange(0, _sample.length)];
[_matches enumerateObjectsUsingBlock:^(NSTextCheckingResult * result, NSUInteger idx, BOOL *stop) {
if (idx == 0) {
NSLog(@"ignoring first occurance...");
} else {
NSLog(@"occurance's index : %d, character's index in string : %d", idx, result.range.location); // that line is simplified for your problem
}
}];
注意:您可以重新排列实际的if
语句,它当前“跳过”第一次出现并打印其余内容 - 但它可以根据您的进一步愿望进行自定义。
我的控制台显示如下内容:
ignoring first occurance...
occurance's index : 1, character's index in string : 5
occurance's index : 2, character's index in string : 23
答案 2 :(得分:0)
NSString *steSample = @"This is sample test string";
NSUInteger count = 0, length = [steSample length];
NSRange range = NSMakeRange(0, length);
while(range.location != NSNotFound)
{
range = [steSample rangeOfString: @"i" options:0 range:range];
if(range.location != NSNotFound)
{
range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
count++;
if (count == 2)
{
NSLog(@"%d", range.location); // print 6 which is location of second 'i'
}
}
}