2

请让我以道歉的方式开始这个问题。我对 Objective C 很陌生。不幸的是,我的工作项目时间很紧,需要尽快跟上进度。

下面的代码有效。我只是想知道是否有更好的方法来处理这个......也许更可可的东西。该函数的全部目的是获取字符串中具有特定值的位置的有序列表。

出于舒适的原因,我回到了标准阵列。我最初声明的 NSMutableString 仅用于测试目的。作为这门语言的一个完整的菜鸟,并且仍然围绕着 Objective C(和我猜的 C++)处理变量和指针的方式,任何和所有的提示、提示、指针都将不胜感激。

NSMutableString *mut = [[NSMutableString alloc] initWithString:@"This is a test of the emergency broadcast system.  This is only a test."];

NSMutableArray *tList = [NSMutableArray arrayWithArray:[mut componentsSeparatedByString:@" "]];

int dump[(tList.count-1)];
int dpCount=0;
NSUInteger length = [mut length];
NSRange myRange = NSMakeRange(0, length);

while (myRange.location != NSNotFound) {

    myRange = [mut rangeOfString:@" " options: 0 range:myRange];

    if (myRange.location != NSNotFound) {
        dump[dpCount]=myRange.location;
        ++dpCount;
        myRange = NSMakeRange((myRange.location+myRange.length), (length - (myRange.location+myRange.length)));
    }
}

for (int i=0; i < dpCount; ++i) {
    //Going to do something with these values in the future... they MUST be in order.
    NSLog(@"Dumping positions in order: %i",dump[i]);
}
text2.text = mut;
[mut release];

再次感谢您的任何回复。

4

2 回答 2

1

没有很好的方法来做你想做的事情。这是一种方法:

// locations will be an NSArray of NSNumbers -- 
// each NSNumber containing one location of the substring):
NSMutableArray *locations = [NSMutableArray new];
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) break;
    [locations addObject:[NSNumber numberWithInt:searchRange.location]];
    searchRange.location = foundRange.location+foundRange.length;
}
于 2012-05-15T23:31:20.460 回答
1

这可能会更精简(如果重要的话,执行时间也会更快):

const char *p = "This is a test of the emergency broadcast system.  This is only a test.";
NSMutableArray *positions = [NSMutableArray array];

for (int i = 0; *p; p++, i++)
{
    if (*p == ' ') {
        [positions addObject:[NSNumber numberWithInt:i]];
    }
}

for (int j = 0; j < [positions count]; j++) {
    NSLog(@"position %d: %@", j + 1, [positions objectAtIndex:j]);
}
于 2012-05-16T00:20:41.690 回答