Getting index of a character in NSString with offset & using substring in Objective-C

前端 未结 1 1229
Happy的楠姐
Happy的楠姐 2021-02-12 12:05

I have a string!

   NSString *myString=[NSString stringWithFormat:@\"This is my lovely string\"];

What I want to do is:

  1. Assuming
相关标签:
1条回答
  • 2021-02-12 13:11
    - (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask range:(NSRange)aRange
    

    For the options use: NSBackwardsSearch

    NSRange range = [myString rangeOfString:@" " options:NSBackwardsSearch range:NSMakeRange(0, 11)];
    

    Example:

    NSString *myString=[NSString stringWithFormat:@"This is my lovely string"];
    NSRange range = [myString rangeOfString:@" " options:NSBackwardsSearch range:NSMakeRange(0, 11)];
    NSLog(@"range.location: %lu", range.location);
    NSString *substring = [myString substringFromIndex:range.location+1];
    NSLog(@"substring: '%@'", substring);
    

    NSLog output:

    range.location: 10
    substring: 'lovely string'
    

    Of course there should be error checking that range.location does not equal NSNotFound

    0 讨论(0)
提交回复
热议问题