1

我有一个在字符串长度上运行的 for 循环。第一个循环查找第二个循环中常见的字符。我想保存数组或字符串中常见的 nameString 的索引。请帮忙。代码在下面提到。

for (int i=0; i < nameString.length; i++) {

        char currentLetter = [nameString characterAtIndex:i];

    for (int j=0; j < partnersNameString.length; j++) {
        if (currentLetter == [partnersNameString characterAtIndex:j]) {

            NSRange range;
            range.length=1;
            range.location=j;
           [partnersNameString replaceCharactersInRange:range withString:@""];
            calculateField.text = partnersNameString;
        }
      }
    }
4

3 回答 3

1

您可以为此使用 NSMutablearray

NSMutableArray myArray = [NSMutableArray new];
for (int i=0; i < nameString.length; i++) {

        char currentLetter = [nameString characterAtIndex:i];

    for (int j=0; j < partnersNameString.length; j++) {
        if (currentLetter == [partnersNameString characterAtIndex:j]) {
            //And add it here
            [myArray addObject:currentLetter];
            NSRange range;
            range.length=1;
            range.location=j;
           [partnersNameString replaceCharactersInRange:range withString:@""];
            calculateField.text = partnersNameString;
        }
      }
    }
于 2012-11-23T12:31:00.657 回答
1

有几种方法可以做您正在寻找的事情:您可以使用带有计数的“普通”C 数组,或者您可以使用NSMutableArray带有包装器的数组。

第一种方法如下所示:

NSUInteger indexes[MAX_LENGTH];
NSUInteger lastIndex = 0;
for (int i=0; i < nameString.length; i++) {
    char currentLetter = [nameString characterAtIndex:i];
    for (int j=0; j < partnersNameString.length; j++) {
        if (currentLetter == [partnersNameString characterAtIndex:j]) {
            indexes[lastIndex++] = i;
            // Go through the rest of your code
            ...
        }
    }
}
for (NSUInteger i = 0 ; i != lastIndex ; i++) {
    NSLog(@"Found match at index %u", indexes[i]);
}

第二种方式看起来很相似,只是现在您需要使用NSNumber将数据包装到NSMutableArray

NSMutableArray *indexes = [NSMutableArray array];
for (int i=0; i < nameString.length; i++) {
    char currentLetter = [nameString characterAtIndex:i];
    for (int j=0; j < partnersNameString.length; j++) {
        if (currentLetter == [partnersNameString characterAtIndex:j]) {
            [indexes addObject[NSNumber numberWithInt:i]];
            // Go through the rest of your code
            ...
        }
    }
}
for (NSNumber in indexes) {
   NSLog(@"Found match at index %i", [[indexes objectAtIndex:i] intValue]);
}
于 2012-11-23T12:40:58.053 回答
1
[myArray addObject:[NSNumber numberWithInt:i]];
于 2012-11-23T12:41:52.833 回答