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

爷,独闯天下 提交于 2019-12-12 07:41:17

问题


I have a string!

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

What I want to do is:

  1. Assuming the first character in the string is at index 0. Go to the 11th character (That is 'l' in the above case), and find the position of first occurring space backwards (In the above string, the position of first occurring space if we go backwards from 'l' is at position 10). Let's call the index of this space 'leSpace' having value 10.
  2. Substring the remaining string to a new string using ...

    [myString substringFromIndex:leSpace]
    

...I hope I have explained well. Please help, can you write a snippet or something to help me do this task?


回答1:


- (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



来源:https://stackoverflow.com/questions/8418184/getting-index-of-a-character-in-nsstring-with-offset-using-substring-in-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!