rangeOfString是一个NSString类的方法,用于在字符串中查找指定的子字符串。它返回一个NSRange结构体,指示子字符串的位置和长度。
用法示例:
- 在字符串中查找子字符串的位置:
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"); }
- 在字符串中查找子字符串的位置和长度:
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选项。