views:

777

answers:

2

I want to split a few strings whose separate marks are different.

e.g.separate a string: "A-B^C~D"

So I want to get the index of each separate mark. Is there any method like indexOf(' ') on iPhone?

+3  A: 

NSString have a bunch of methods for finding characters and substrings. They are basically variants of these two:

- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet

- (NSRange)rangeOfString:(NSString *)aString

The returned NSRange have a location and length field. If it couldn't find part location will be set to NSNotFound

But it looks like you should use the method

- (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator

That will return an array with the separated parts.

epatel
A: 

This code will return the position of the character in the string.

NSString *myString = @"A-B^C~D";
int dash = [myString rangeOfString:@"-"].location;
int power = [myString rangeOfString:@"^"].location;
int squiggle = [myString rangeOfString:@"~"].location;
woot586