请允许我在这个问题前表达歉意。我对 Objective C 非常陌生。不幸的是,我的工作项目时间非常紧迫,需要尽快跟上进度。
下面的代码有效。我只是想知道是否有更好的方法来处理这个问题......也许是更 cocoa 的东西。该函数的全部目的是获取字符串中具有特定值的位置的有序列表。
出于舒适原因,我选择了标准阵列。我最初声明的 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];
再次感谢您的回复。
最佳答案
没有什么好方法可以完成您想要做的事情。这是一种方法:
// 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;
}
关于iphone - 在 Objective-C 中处理数组的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10610080/