我试图弄清楚如何在字符串中获取一系列子字符串.按范围我的意思是子串开始的位置和结束的位置.所以,如果我有以下字符串示例:
NSString *testString=@"hello everyone how are you doing today?Thank you!";
Run Code Online (Sandbox Code Playgroud)
如果我要查找的子字符串(在这个例子中)是"你好吗",那么起始范围应为15,结束范围应为31.
(15, 31)
Run Code Online (Sandbox Code Playgroud)
任何人都可以告诉我如何以编程方式执行此操作?谢谢!
max*_*ax_ 47
您可以使用该方法-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);
}
Run Code Online (Sandbox Code Playgroud)
Tre*_*kow 10
这很直截了当.你说你想搜索字符串"大家好,你今天好吗?谢谢!" 因为"你好吗".
你说你需要第一个角色和最后一个角色的位置.
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;
Run Code Online (Sandbox Code Playgroud)
所以现在你有了最后两个变量.
| 归档时间: |
|
| 查看次数: |
29106 次 |
| 最近记录: |