NSRangeFromString(<#NSString * _Nonnull aString#>) 和rangeOfString

时间:2024-06-08 14:37:14

NSRangeFromString

NSString *str1 = @"abcdef";
NSString *str2 = @"1-105";
NSString *str3 = @"13";
NSString *str4 = @"13 34";
NSString *str5 = @"15 32 77";
NSRange range = NSRangeFromString(str1);
NSLog(@"\nlocation:%ld length:%ld", range.location, range.length);
//location:0 length:0 range = NSRangeFromString(str2);
NSLog(@"\nlocation:%ld length:%ld", range.location, range.length);
//location:1 length:105 range = NSRangeFromString(str3);
NSLog(@"\nlocation:%ld length:%ld", range.location, range.length);
//location:13 length:0 range = NSRangeFromString(str4);
NSLog(@"\nlocation:%ld length:%ld", range.location, range.length);
//location:13 length:34 range = NSRangeFromString(str5);
NSLog(@"\nlocation:%ld length:%ld", range.location, range.length);
//location:15 length:32

rangeOfString

NSString *homebrew = @"Imperial India Pale Ale (IPA)";

// Search for the "ia" starting at the end of string

NSRange range = [homebrew rangeOfString:@"ia" options:NSBackwardsSearch];

// What did we find

if (range.length > 0)

  NSLog(@"Range is: %@", NSStringFromRange(range));

//上面的程序将输出:Range is: {12, 2}