ios 查找字符串子串的范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16998478/
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 23:49:56  来源:igfitidea点击:

find range of substring of string

iosobjective-c

提问by Teddy13

I am trying to figure out how to get a range of a substring within a string. By range I mean where the substring begins and where it ends. So if I have following string example:

我想弄清楚如何在字符串中获取子字符串的范围。我所说的范围是指子字符串的开始和结束位置。因此,如果我有以下字符串示例:

NSString *testString=@"hello everyone how are you doing today?Thank you!";

If the substring I am looking for (in this example) is "how are you doing", then the beginning range should be 15 and the ending range should 31.

如果我正在寻找的子字符串(在本例中)是“你好吗”,那么开始范围应该是 15,结束范围应该是 31。

  (15, 31)

Can anyone tell me how I could do this programatically? Thank you!

谁能告诉我如何以编程方式做到这一点?谢谢!

回答by max_

You can use the method -rangeOfStringto find the location of a substring in a string. You can then compare the location of the range to NSNotFound to see if the string actually does contain the substring.

您可以使用该方法-rangeOfString查找子字符串在字符串中的位置。然后,您可以将范围的位置与 NSNotFound 进行比较,以查看字符串是否确实包含子字符串。

NSRange range = [testString rangeOfString:@"how are you doing"];

if (range.location == NSNotFound) {
    NSLog(@"The string (testString) does not contain 'how are you doing' as a substring");
}
else {
    NSLog(@"Found the range of the substring at (%d, %d)", range.location, range.location + range.length);        
}

回答by Trenskow

It is pretty straight forward. You say you want to search the string "hello everyone how are you doing today?Thank you!" for "how are you doing".

这是非常直接的。您说要搜索字符串“大家好,今天过得好吗?谢谢!” 因为“你好吗”。

You say you need the position of the first character and the last.

你说你需要第一个字符和最后一个字符的位置。

NSString *testString=@"hello everyone how are you doing today?Thank you!";

NSRange range = [testString rangeOfString:@"how are you doing"];

NSUInteger firstCharacterPosition = range.location;
NSUInteger lastCharacterPosition = range.location + range.length;

So now you have it those two last variables.

所以现在你有了最后两个变量。