我有一个在字符串长度上运行的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;
}
}
}
答案 0 :(得分: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;
}
}
}
答案 1 :(得分: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]);
}
答案 2 :(得分:1)
[myArray addObject:[NSNumber numberWithInt:i]];