How to find the substring between two string? [closed]

廉价感情. 提交于 2019-12-20 10:28:12

问题


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?


回答1:


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



回答2:


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



回答3:


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:


Use substringWithRange...

NSString* substring = [originalString substringWithRange:NSMakeRange(3, originalString.length-6)];


来源:https://stackoverflow.com/questions/15339174/how-to-find-the-substring-between-two-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!