How to find the substring between two string? [clo

2019-03-12 10:10发布

I have a string "hi how are... you"

I want to find the Sub-string after how and before you..

How to do this in objective c?

4条回答
Luminary・发光体
2楼-- · 2019-03-12 10:49

You could use the method of NSString substringWithRange

Example

NSString *string=@"hi how are you";
NSRange searchFromRange = [string rangeOfString:@"how"];
NSRange searchToRange = [string rangeOfString:@"you"];
NSString *substring = [string substringWithRange:NSMakeRange(searchFromRange.location+searchFromRange.length, searchToRange.location-searchFromRange.location-searchFromRange.length)];
NSLog(@"subs=%@",substring); //subs= are
查看更多
Animai°情兽
3楼-- · 2019-03-12 10:54

use SubstringTOIndex & SubstringFromIndex functions of NSString. Where SubstringFromIndex gives you the string from the index which you passed & SubstringToIndex function gives you the string upto the index which you passed.

Also try substringWithRange function which returns you the string between the range which you passed.

查看更多
等我变得足够好
4楼-- · 2019-03-12 10:59

Use substringWithRange...

NSString* substring = [originalString substringWithRange:NSMakeRange(3, originalString.length-6)];
查看更多
兄弟一词,经得起流年.
5楼-- · 2019-03-12 11:04

Find the range of the two strings and return the substring in between:

NSString *s = @"hi how are... you";

NSRange r1 = [s rangeOfString:@"how"];
NSRange r2 = [s rangeOfString:@"you"];
NSRange rSub = NSMakeRange(r1.location + r1.length, r2.location - r1.location - r1.length);
NSString *sub = [s substringWithRange:rSub];
查看更多
登录 后发表回答