开发者

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" 开发者_如何学Cand make a substring that will be "the cat".

Can someone help me out or give me an example?

Thanks,

Sagiftw


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


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.


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


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.


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

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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜