Objective-C中NSRange的问题?

时间:2011-01-06 14:56:24

标签: iphone objective-c nsstring nsrange

我对NSRange有一点问题,或者可能是我使用的错误的命令。

这是我想要做的。我有一个这样的字符串:

NSString *mystring = @"/c1blue/c2green/c3yellow/"

正如您所看到的,总会有一个带有值的命令,并且用“/”分隔。现在我想写一个mthod,它为我提供了一个特定的命令值,例如c2是绿色的。

首先我会得到c2的位置:

int beginIndex = [mystring rangeOfString:@"c2"].location;

现在我需要找到“/”的位置,偏移量为'beginIndex'。

那就是我不知道的地方。

非常感谢帮助。 感谢

5 个答案:

答案 0 :(得分:3)

如何使用componentsSeparatedByString:的{​​{1}}方法首先将字符串拆分为数组?

答案 1 :(得分:2)

这个怎么样:

NSString *mystring = @"/c1blue/c2green/c3yellow/";
NSMutableDictionary *commands=[NSMutableDictionary dictionary];
for (NSString *component in [mystring componentsSeparatedByString:@"/"])
{
    // assuming your identifier is always 2 characters...
    if ([component length]>2) {
        [commands setObject:[component substringFromIndex:2] forKey:[component substringToIndex:2]];
    }
}
NSLog(@"commands %@", commands);
NSLog(@"command c2: %@", [commands objectForKey:@"c2"]);

结果:

2011-01-06 15:21:27.117 so[3741:a0f] commands {
    c1 = blue;
    c2 = green;
    c3 = yellow;
}
2011-01-06 15:25:26.488 so[3801:a0f] command c2: green

答案 2 :(得分:1)

另一种方法:

NSString *getCommand(NSString *string, NSString *identifier)
{
    for (NSString *component in [string componentsSeparatedByString:@"/"])
    {
        NSRange range=[component rangeOfString:identifier];
        if (range.location==0) {
            return [component substringFromIndex:range.length];
        }
    }
    return nil;
}

测试代码:

NSString *mystring = @"/c1blue/c2green/c3yellow/";
NSLog(@"%@", getCommand(mystring, @"c2"));
NSLog(@"%@", getCommand(mystring, @"c3"));
NSLog(@"%@", getCommand(mystring, @"c4"));  

结果:

2011-01-06 15:31:13.706 so[3949:a0f] green
2011-01-06 15:31:13.711 so[3949:a0f] yellow
2011-01-06 15:31:13.712 so[3949:a0f] (null)

答案 3 :(得分:0)

查看NSString参考资料,我认为您需要的是:

- (NSArray *)componentsSeparatedByString:(NSString *)separator

答案 4 :(得分:0)