-1

How do I split a URL by the / character?

For example,

www.stackoverflow.com/questions

I want to split after / in the above URL to get /questions

weiyin
  • 6,819
  • 4
  • 47
  • 58
B.Saravana Kumar
  • 1,208
  • 6
  • 20
  • 48

2 Answers2

2

This may help you.

NSString *url = @"www.stackoverflow.com/questions";
NSArray *items = [url componentsSeparatedByString:@"/"];

NSString *str1=[items objectATindex:0];   //www.stackoverflow.com
NSString *str2=[items objectATindex:1];   //questions
technerd
  • 14,144
  • 10
  • 61
  • 92
1

Use the pathComponents property on an NSURL object.

This property contains an array containing the individual path components of the URL, each unescaped using the stringByReplacingPercentEscapesUsingEncoding: method. For example, in the URL file:///directory/directory%202/file, the path components array would be @[@"/", @"directory", @"directory 2", @"file"].

NSURL *myUrl = [NSURL URLWithString:@"www.stackoverflow.com/questions"];
NSString *lastPathComponent = [myUrl lastPathComponent]; // "questions"
NSArray *pathComponents = [myUrl pathComponents]; // <__NSArrayM 0x7fc45b649df0>( www.stackoverflow.com, questions )

To remove the http://, use host property:

NSURL *myUrl = [NSURL URLWithString:@"http://www.stackoverflow.com/questions"];
NSString *host = myUrl.host; // stackoverflow.com
JAL
  • 41,701
  • 23
  • 172
  • 300