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!

1
  • 1
    Do these strings represent file paths? Commented Apr 30, 2013 at 7:19

6 Answers 6

5

You are looking for the componentsSeparatedByString: method

NSString *originalString = @"word1/word2/word3";
NSArray *separatedArray = [originalString componentsSeparatedByString:@"/"];
NSString *lastObject = [separatedArray lastObject]; //word3
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

@user1014334:no need to take array use NSString class methods.
2

you must use NSScanner class to split substring.

check this.

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

Comments

2
NSString *string = @"word1/word2/word3"
NSArray *arr = [string componentsSeperatedByString:@"/"];
NSSting *str = [arr lastObject];

1 Comment

What I meant is that the "Words" can be anything. and not only "word 1 word 2 word 3" sorry for not explaining well...
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];

Comments

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.