findstring的子串的范围
我想弄清楚如何获得一个string中的子string的范围。 按范围我是指子string开始和结束的地方。 所以如果我有以下string的例子:
NSString *testString=@"hello everyone how are you doing today?Thank you!";
如果我正在查找的子string(在本例中)是“你好吗”,那么开始范围应该是15,结束范围应该是31。
(15, 31)
任何人都可以告诉我如何编程方式吗? 谢谢!
您可以使用method -rangeOfString
来查找string-rangeOfString
string的位置。 然后,您可以将范围的位置与NSNotFound进行比较,以查看该string是否确实包含子string。
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); }
这非常简单。 你说你想searchstring“你好,大家今天过得怎么样?谢谢!” 为“你好吗”。
你说你需要第一个字符和最后一个字符的位置。
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;
所以现在你有这两个最后的variables。
使用NSString
的内置方法部分:
[testString rangeOfString:@"hello how are you doing"]
文档: https : //developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/doc/uid/20000154-rangeOfString_