13
NSString *url = @"http://stackoverflow.com/questions/ask"; 

How can I get the character position of the 4th "/" ?

1
  • What you mean by 4th "/", first the 4th character is not "/". Or if you mean the the 4th "/" in all "/", which corresponds to the last one "/ask" Commented Sep 3, 2010 at 2:22

4 Answers 4

29

If you're just trying to get the last part of the url, you should be able to use this:

NSArray* items = [url componentsSeparatedByString:@"/"]; 

To get the index of the last '/' character:

NSRange range = [url rangeOfString:@"/" options:NSBackwardsSearch]; 

get the index value from range.location

To find the index of the fourth '/' character from the url:

int count = 0; int index = -1; for (unsigned int i=0; i < [url length]; ++i) { if ([url characterAtIndex:i] == '/') { ++count; if (count == 4) { index = i; break; } } } 
Sign up to request clarification or add additional context in comments.

1 Comment

it's not always the last one, it's the 4th one
7

Usually you don't have to get the index of the letter /. You can just use many convenience methods defined in NSURL, see this Apple reference. I would do

 NSURL* url=[NSURL URLWithString:@"http://stackoverflow.com/questions/ask"]; NSString* last=[url lastPathComponent]; // last is now @"ask" 

Comments

5

another way you can use

[url rangeOfString:@"/" options:NSBackwardsSearch].location 

hope it help!

1 Comment

I was just trying to figure out how to manually do "logical" linebreaks on a string (i.e. breaking at a space) to spit out a string in multiple CCLabelTTF blocks, and this was exactly what I needed, thanks!
0

I editted my answer after understanding your problem.

The answer of Hitesh it almost correct, you just need to do a little bit more

NSArray* items = [url componentsSeparatedByString:@"/"]; if ([items count] > 4) { NSString *string = [items objectAtIndex:4]; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.