0

Hello everyone I am trying find a string inside a string lets say I have a string:

word1/word2/word3

I want to find the word from the end of the string to the last "/" so what I will get from that string is:

Word3

How do I do that? Thanks!

Matan
  • 456
  • 2
  • 8
  • 18

6 Answers6

5

You are looking for the componentsSeparatedByString: method

NSString *originalString = @"word1/word2/word3";
NSArray *separatedArray = [originalString componentsSeparatedByString:@"/"];
NSString *lastObject = [separatedArray lastObject]; //word3
txulu
  • 1,602
  • 16
  • 26
3

once check this one By using this one you'l get last pathcomponent values,

NSString* theFileName = @"how /are / you ";
    NSString *str1=[theFileName lastPathComponent];
    NSLog(@"%@",str1);

By using lastPathComponent you'l get the last path component directly no need to take array for separate the string.

Balu
  • 8,470
  • 2
  • 24
  • 41
2
NSString *string = @"word1/word2/word3"
NSArray *arr = [string componentsSeperatedByString:@"/"];
NSSting *str = [arr lastObject];
Girish
  • 4,692
  • 4
  • 35
  • 55
  • What I meant is that the "Words" can be anything. and not only "word 1 word 2 word 3" sorry for not explaining well... – Matan Apr 30 '13 at 07:15
2

you must use NSScanner class to split substring.

check this.

Objective C: How to extract part of a String (e.g. start with '#')

Community
  • 1
  • 1
Suraj Gupta
  • 200
  • 9
2

You can find it also with this way:

NSMutableString *string=[NSMutableString stringWithString:@"word1/word2/word3"];
NSRange range=[string rangeOfString:@"/" options:NSBackwardsSearch];
NSString *subString=[string substringFromIndex:range.location+1];
Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
1

NSRegularExpression or NSString rangeOfString:options:range:locale: (with options to search backwards).

The answer really depends on exactly what the input string will contain (how consistent it is).

Wain
  • 118,658
  • 15
  • 128
  • 151