ios 如何找到两个字符串之间的子字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15339174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find the substring between two string?
提问by Raju
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?
如何在目标 c 中做到这一点?
回答by
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];
回答by nsgulliver
You could use the method of NSString substringWithRange
你可以使用 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
回答by Girish
use SubstringTOIndex& SubstringFromIndexfunctions of NSString. Where SubstringFromIndexgives you the stringfrom the index which you passed & SubstringToIndexfunction gives you the stringupto the index which you passed.
的用途SubstringTOIndex和SubstringFromIndex功能NSString。WhereSubstringFromIndex为您提供string从您传递的索引开始,SubstringToIndex函数为您提供了string您传递的索引。
Also try substringWithRangefunction which returns you the stringbetween the range which you passed.
还可以尝试substringWithRange返回string您传递的范围之间的函数。
回答by jjv360
Use substringWithRange...
使用substringWithRange...
NSString* substring = [originalString substringWithRange:NSMakeRange(3, originalString.length-6)];

