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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 22:39:28  来源:igfitidea点击:

How to find the substring between two string?

iosobjective-cios5ios6ios4

提问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.

的用途SubstringTOIndexSubstringFromIndex功能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)];