iphone - 在 Objective-C 中处理数组的更好方法?

标签 iphone objective-c arrays nsmutablestring

请允许我在这个问题前表达歉意。我对 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/

相关文章:

iphone - UITableViewCell 中的 UILabel 无需创建单独的类即可创建自定义单元格

objective-c - 连接到多个 Controller 的 iOS subview 小部件

javascript - 如何使用自定义 jsonification 对包含对象的数组进行 jsonify

iphone - 使用推送通知服务有任何费用吗?

IOS企业应用无法安装请稍后重试

iphone - 如何在 iOS 中制作自己的自定义日历

ios - 如何用白色初始化 UIColor

objective-c - 类组合在 iOS 中是如何工作的?

c - 在 C 中搜索 char 数组以查找数组中的位置

arrays - 简单的工作表循环并将单元格值放入 vba 数组