Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString character position

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

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

like image 459
Fasid Avatar asked Sep 03 '10 02:09

Fasid


People also ask

What is NSString in Objective C?

(NSString *) is simply the type of the argument - a string object, which is the NSString class in Cocoa. In Objective-C you're always dealing with object references (pointers), so the "*" indicates that the argument is a reference to an NSString object.

What is NSString in swift?

NSString : Creates objects that resides in heap and always passed by reference. String: Its a value type whenever we pass it , its passed by value. like Struct and Enum, String itself a Struct in Swift.


2 Answers

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;
        }
    }
}
like image 79
Hitesh Avatar answered Oct 04 '22 10:10

Hitesh


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"
like image 26
Yuji Avatar answered Oct 04 '22 12:10

Yuji