Finding a substring in a NSString object

Objective CStringNsstringSubstring

Objective C Problem Overview


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

Objective C Solutions


Solution 1 - Objective C

NSRange range = [string rangeOfString:@"ate"];
NSString *substring = [[string substringFromIndex:NSMaxRange(range)] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

Solution 2 - Objective C

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.

Solution 3 - Objective C

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];

Solution 4 - Objective C

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.

Solution 5 - Objective C

NSString *theNewString = [receivedString substringFromIndex:[receivedString rangeOfString:@"Ur String"].location];

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

Solution 6 - Objective C

-(BOOL)Contains:(NSString *)StrSearchTerm on:(NSString *)StrText
{
   return  [StrText rangeOfString:StrSearchTerm options:NSCaseInsensitiveSearch].location==NSNotFound?FALSE:TRUE;
}

Solution 7 - Objective C

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSagiftwView Question on Stackoverflow
Solution 1 - Objective CJoostView Answer on Stackoverflow
Solution 2 - Objective CjtbandesView Answer on Stackoverflow
Solution 3 - Objective CSedat KilincView Answer on Stackoverflow
Solution 4 - Objective CSumit SharmaView Answer on Stackoverflow
Solution 5 - Objective CPradeep Reddy KypaView Answer on Stackoverflow
Solution 6 - Objective CSandeep SinghView Answer on Stackoverflow
Solution 7 - Objective CAbhishek BhardwajView Answer on Stackoverflow