I have a little problem with NSRange, or maybe its just the wrong comman I use.
Here is what I want to do. I have a string like this :
NSString *mystring = @"/c1blue/c2green/c3yellow/"
As you can see there is always a command with a value and that seperated by "/". Now I want to write a mthod that gives me a specific value for a command, e.g. c2 which would be green.
First I would get the position of c2 :
int beginIndex = [mystring rangeOfString:@"c2"].location;
Now I need to find the position of the "/" with the offset of 'beginIndex'.
And thats where I do not know how.
Help is hihly appreciated. Thanks
Another approach:
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;
}
Test code:
NSString *mystring = @"/c1blue/c2green/c3yellow/";
NSLog(@"%@", getCommand(mystring, @"c2"));
NSLog(@"%@", getCommand(mystring, @"c3"));
NSLog(@"%@", getCommand(mystring, @"c4"));
Result:
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)