温馨提示×

iOS开发中rangeOfString怎么使用

iOS
小亿
278
2023-09-14 22:54:33
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

rangeOfString是一个NSString类的方法,用于在字符串中查找指定的子字符串。它返回一个NSRange结构体,指示子字符串的位置和长度。

用法示例:

  1. 在字符串中查找子字符串的位置:
NSString *string = @"Hello, World!";
NSString *substring = @"World";
NSRange range = [string rangeOfString:substring];
if (range.location != NSNotFound) {
// 子字符串存在于原字符串中
NSLog(@"Substring found at index %lu", range.location);
} else {
// 子字符串不存在于原字符串中
NSLog(@"Substring not found");
}
  1. 在字符串中查找子字符串的位置和长度:
NSString *string = @"Hello, World!";
NSString *substring = @"World";
NSRange range = [string rangeOfString:substring];
if (range.location != NSNotFound) {
// 子字符串存在于原字符串中
NSLog(@"Substring found at index %lu, length %lu", range.location, range.length);
} else {
// 子字符串不存在于原字符串中
NSLog(@"Substring not found");
}

注意:rangeOfString方法是区分大小写的,如果需要进行不区分大小写的查找,可以使用rangeOfString:options:方法,并指定NSCaseInsensitiveSearch选项。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:ios中rangeofstring如何优化内存使用

0