Finding a substring in an NSString object

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

For example, my line is: β€œThe dog ate the cat”, I want the program to find the word β€œate” and create a substring that will be β€œcat”.

Can someone help me or give me an example?

Thank,

Sagiftw

+48
string substring objective-c nsstring
Aug 31 '10 at 22:08
source share
7 answers
NSRange range = [string rangeOfString:@"ate"]; NSString *substring = [[string substringFromIndex:NSMaxRange(range)] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; 
+80
Aug 31 '10 at 10:11
source share
 NSString *str = @"The dog ate the cat"; NSString *search = @"ate"; NSString *sub = [str substringFromIndex:NSMaxRange([str rangeOfString:search])]; 

If you want to trim spaces, you can do it separately.

+16
Aug 31 '10 at 10:11
source share

How about this? It is almost the same. But maybe the meaning of NSRange is easier for beginners to understand if he writes like this.

Finally, this is the same jtbandes solution

  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]; 
+8
Feb 05 '13 at 13:08
source share

Try it.

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

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

+3
04 Sep '15 at 13:26
source share
 NSString *theNewString = [receivedString substringFromIndex:[receivedString rangeOfString:@"Ur String"].location]; 

You can find the string and then get the search string in another string ...

+2
May 11 '12 at 7:00
source share
 -(BOOL)Contains:(NSString *)StrSearchTerm on:(NSString *)StrText { return [StrText rangeOfString:StrSearchTerm options:NSCaseInsensitiveSearch].location==NSNotFound?FALSE:TRUE; } 
+1
Dec 17 '13 at 6:39
source share

You can use either of the two methods provided in the NSString class, for example substringToIndex: and substringFromIndex: Pass it NSRange as the length and location, and you will get the desired result.

0
Sep 04 '15 at 17:59 on
source share



All Articles