我正在尝试弄清楚如何获得字符串中的子字符串的范围。我所说的范围是指子串开始和结束的地方。因此,如果我有以下字符串示例:
NSString *testString=@"hello everyone how are you doing today?Thank you!";
如果我要查找的子字符串(在本例中)是"how are you 31“,那么开始范围应该是15,结束范围应该是31。
(15, 31)
有人能告诉我如何通过编程来做到这一点吗?谢谢!
发布于 2013-06-08 18:22:34
您可以使用-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);
}
发布于 2013-06-08 18:55:32
这是非常直接的。你说你想搜索字符串“大家好,你今天好吗?谢谢!”表示“你好吗?”
你说你需要第一个字符和最后一个字符的位置。
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;
现在你有了最后两个变量。
https://stackoverflow.com/questions/16998478
复制相似问题