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

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

Position of a Substring in NSString

iphoneobjective-ciosxcodeios4

提问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:2147483647when searchKeywordis a substring within string.

这将返回index:2147483647whensearchKeyword是 中的子字符串string

How i can get the index value like 20or 5like that?

我如何获得类似205类似的索引值?

回答by Lily Ballard

2147483647is 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....

可能这将帮助你....