ios 子串在 NSString 中的位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11239461/
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
Position of a Substring in NSString
提问by Shaheen Rehman
How I can get the position/Index of a substring within an NSString
?
如何获取NSString
?中子字符串的位置/索引?
I am finding the location in the following way.
我正在通过以下方式找到位置。
NSRange range = [string rangeOfString:searchKeyword];
NSLog (@"match found at index:%u", range.location);
This returns index:2147483647
when searchKeyword
is a substring within string
.
这将返回index:2147483647
whensearchKeyword
是 中的子字符串string
。
How i can get the index value like 20
or 5
like that?
我如何获得类似20
或5
类似的索引值?
回答by Lily Ballard
2147483647
is the same thing as NSNotFound
, which means the string you searched for (searchKeyword
) wasn't found.
2147483647
与 相同NSNotFound
,这意味着searchKeyword
未找到您搜索的字符串 ( )。
NSRange range = [string rangeOfString:searchKeyword];
if (range.location == NSNotFound) {
NSLog(@"string was not found");
} else {
NSLog(@"position %lu", (unsigned long)range.location);
}
回答by Abhishek
NSString *searchKeyword = @"your string";
NSRange rangeOfYourString = [string rangeOfString:searchKeyword];
if(rangeOfYourString.location == NSNotFound)
{
// error condition — the text searchKeyword wasn't in 'string'
}
else{
NSLog(@"range position %lu", rangeOfYourString.location);
}
NSString *subString = [string substringToIndex:rangeOfYourString.location];
may this will help you....
可能这将帮助你....