Chilly Zhong
Chilly Zhong

Reputation: 16783

How to return the index of a character in string on iPhone?

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?

Upvotes: 1

Views: 3569

Answers (2)

woot586
woot586

Reputation: 3965

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;

Upvotes: 2

epatel
epatel

Reputation: 46051

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.

Upvotes: 3

Related Questions