Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a substring in a NSString object

I have an NSString object and I want to make a substring from it, by locating a word.

For example, my string is: "The dog ate the cat", I want the program to locate the word "ate" and make a substring that will be "the cat".

Can someone help me out or give me an example?

Thanks,

Sagiftw

like image 621
Sagiftw Avatar asked Aug 31 '10 22:08

Sagiftw


2 Answers

NSRange range = [string rangeOfString:@"ate"];
NSString *substring = [[string substringFromIndex:NSMaxRange(range)] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
like image 142
Joost Avatar answered Oct 14 '22 18:10

Joost


NSString *str = @"The dog ate the cat";
NSString *search = @"ate";
NSString *sub = [str substringFromIndex:NSMaxRange([str rangeOfString:search])];

If you want to trim whitespace you can do that separately.

like image 16
jtbandes Avatar answered Oct 14 '22 20:10

jtbandes