views:

61

answers:

3

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

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

A: 

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];
}
vodkhang
+1  A: 

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;
        }
    }
}
Hitesh
i need to get the index but thx
Fasid
it's not always the last one, it's the 4th one
Fasid
+1  A: 

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"
Yuji