Finding a substring in a NSString object

2019-01-04 11:09发布

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

7条回答
Rolldiameter
2楼-- · 2019-01-04 11:32
NSString *theNewString = [receivedString substringFromIndex:[receivedString rangeOfString:@"Ur String"].location];

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

查看更多
Rolldiameter
3楼-- · 2019-01-04 11:36

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.

查看更多
孤傲高冷的网名
4楼-- · 2019-01-04 11:37

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.

查看更多
Anthone
5楼-- · 2019-01-04 11:51
NSRange range = [string rangeOfString:@"ate"];
NSString *substring = [[string substringFromIndex:NSMaxRange(range)] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
查看更多
别忘想泡老子
6楼-- · 2019-01-04 11:51
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.

查看更多
兄弟一词,经得起流年.
7楼-- · 2019-01-04 11:51

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];
查看更多
登录 后发表回答