我有一个NSString例如"This is my question"
。我想找到字符/子串"i"
的所有索引,即在这种情况下如果索引从0
开始,那么我想要{ {1}}作为我的答案。
答案 0 :(得分:4)
另一个答案是有点矫枉过正。你为什么不简单地迭代这样的字符:
NSString *x = @"This is my question";
for (NSUInteger i=0;i<[x length];i++)
{
if ([x characterAtIndex:i]=='i')
{
NSLog(@"found: %d", i);
}
}
它完全输出你的位置:
found: 2
found: 5
found: 16
答案 1 :(得分:1)
我想建议我的解决方案。就像这样:
NSString* str = @"This is my question";
NSArray* arr = [str componentsSeparatedByString: @"i"];
NSMutableArray* marr = [NSMutableArray arr];
NSInteger cnt = 0;
for (NSInteger i = 0; i < ([arr count]); i++)
{
NSString* s = [arr objectAtIndex: i];
cnt += [s length];
[marr addObject: [NSNumber numberWithInt: cnt]];
cnt += [@"i" length];
}
NSLog(@"%@", [marr description]);
在控制台上: 2 五 16
答案 2 :(得分:0)
使用NSRange
和循环以及一些字符串操作,您可以轻松完成。
NSString *string = @"This is my question";
NSString *substring = @"i";
NSRange searchRange = NSMakeRange(0,string.length);
NSRange foundRange;
while (searchRange.location < string.length)
{
searchRange.length = string.length-searchRange.location;
foundRange = [string rangeOfString:substring options:nil range:searchRange];
if (foundRange.location != NSNotFound)
{
// found an occurrence of the char
searchRange.location = foundRange.location+foundRange.length;
NSLog(@"Location of '%@' is %d",substring,searchRange.location-1);
}
}
修改强>
使用NSRegularExpression
和NSRange
,您可以这样做。
NSString *string = @"This is my question";
NSString *substring = @"i";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:substring
options:0
error:NULL];
[regex enumerateMatchesInString:string options:0 range:NSMakeRange(0, [string length])
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
NSRange range = [result range];
NSLog(@"Location of '%@' is %d",substring, range.location);
}];
输出
Location of 'i' is 2
Location of 'i' is 5
Location of 'i' is 16
答案 3 :(得分:0)
我不知道有没有可用的内置函数。您可以使用此方法:
- (NSMutableArray *)indexOfCharacter:(char)c inString:(NSString*)string
{
NSMutableArray *returnArray = [[NSMutableArray alloc] init];
for(int i=0;i<string.length;i++)
{
if(c == [string characterAtIndex:i])
{
[returnArray addObject:[NSNumber numberWithInt:i]];
}
}
return returnArray;
}
答案 4 :(得分:0)
这是我尝试获得你想要的无循环代码。我把这个盲目编码,意思是未经测试等等。它基本上是一个递归函数,但我认为它可以让你了解一般。
- (NSArray *)getAllEyes:(NSString *)s index:(int)index) {
if (!s || s.length <= 0 || index >= s.length) return [NSArray new];
NSRange *r = [s rangeOfString(@"i") options:NSLiteralSearch range:NSMakeRange(index, s.length - index)];
if (r.location == NSNotFound) {
return [NSArray new];
} else {
NSMutableArray *array = [NSMutableArray new];
[array addObject:@(r.location)];
[array addObjectsFromArray:[self getAllEyes:s index:r.location + 1]];
return array;
}
}
// usage:
NSArray *allEyes = [self getAllEyes:@""];
for (NSNumber *n in allEyes) {
NSLog(@"i = %@", n);
}