Reputation: 2666
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
Upvotes: 2
Views: 3446
Reputation: 2666
Thanks,
I actually came up with this one, but it looks more complicated than the suggested ones :
- (NSString *) CommSubStr:(NSString *) commandString withPattern:(NSString *) command
{
int beginIndex = [commandString rangeOfString:command].location;
if (beginIndex == -1)
{
return @"";
} else
{
NSRange subStringRange = NSMakeRange(beginIndex + [command length], [commandString length]-(beginIndex+[command length]));
NSString *newString = [commandString substringWithRange:subStringRange];
int endIndex = [newString rangeOfString:@"/"].location;
NSRange finalSubStringRange = NSMakeRange(0, endIndex);
return [newString substringWithRange:finalSubStringRange];
}
}
Upvotes: 0
Reputation: 15857
How about this:
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"]);
Result:
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
Upvotes: 2
Reputation: 15857
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)
Upvotes: 1
Reputation: 12036
Look at NSString reference and i think what you need is:
- (NSArray *)componentsSeparatedByString:(NSString *)separator
Upvotes: 0
Reputation: 104065
How about splitting the string into array first, using the componentsSeparatedByString:
method of NSString
?
Upvotes: 3