50

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

phaxian
  • 1,058
  • 16
  • 28
Sagiftw
  • 1,658
  • 4
  • 21
  • 25

7 Answers7

83
NSRange range = [string rangeOfString:@"ate"];
NSString *substring = [[string substringFromIndex:NSMaxRange(range)] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
Joost
  • 10,333
  • 4
  • 55
  • 61
  • 4
    I know this topic is old, but FWIW, you can also use rangeOfString:options: where in options you use NSCaseInsensitiveSearch if case is an issue. That is, if a user could enter a string in any case, and you just want to know whether a pattern is there, regardless of case, you would use the case-insensitive search. – GTAE86 Nov 15 '13 at 21:56
16
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.

jtbandes
  • 115,675
  • 35
  • 233
  • 266
8

What about this way? It's nearly the same. But maybe meaning of NSRange easier to understand for beginners, if it's written this way.

At last, it's the same solution of jtbandes

    NSString *szHaystack= @"The dog ate the cat";
    NSString *szNeedle= @"ate";
    NSRange range = [szHaystack rangeOfString:szNeedle];
    NSInteger idx = range.location + range.length;
    NSString *szResult = [szHaystack substringFromIndex:idx];
Sedat Kilinc
  • 2,843
  • 1
  • 22
  • 20
3

Try this one..

BOOL isValid=[yourString containsString:@"X"];

This method return true or false. If your string contains this character it return true, and otherwise it returns false.

josliber
  • 43,891
  • 12
  • 98
  • 133
Sumit Sharma
  • 443
  • 3
  • 8
2
NSString *theNewString = [receivedString substringFromIndex:[receivedString rangeOfString:@"Ur String"].location];

You can search for a string and then get the searched string into another string...

Garoal
  • 2,364
  • 2
  • 19
  • 31
Pradeep Reddy Kypa
  • 3,992
  • 7
  • 57
  • 75
1
-(BOOL)Contains:(NSString *)StrSearchTerm on:(NSString *)StrText
{
   return  [StrText rangeOfString:StrSearchTerm options:NSCaseInsensitiveSearch].location==NSNotFound?FALSE:TRUE;
}
Nazik
  • 8,696
  • 27
  • 77
  • 123
Sandeep Singh
  • 268
  • 1
  • 9
0

You can use any of the two methods provided in NSString class, like substringToIndex: and substringFromIndex:. Pass a NSRange to it as your length and location, and you will have the desired output.

Aviram
  • 3,017
  • 4
  • 29
  • 43