使用offset&获取NSString中字符的索引在Objective-C中使用子字符串 [英] Getting index of a character in NSString with offset & using substring in Objective-C

查看:91
本文介绍了使用offset&获取NSString中字符的索引在Objective-C中使用子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串!

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

我想做的是:


  1. 假设字符串中的第一个字符是索引0.转到第11个字符(在上面的情况下是'l'),并找到第一个出现空格的位置(在上面)如果我们从'l'向后移动,则第一个出现空间的位置在第10位。让我们调用此空间'leSpace'的索引值为10.

  2. 使用...将剩余字符串子串到一个新字符串

  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?

推荐答案

- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask range:(NSRange)aRange

对于选项使用: NSBackwardsSearch

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

示例:

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输出:

range.location: 10
substring: 'lovely string'

当然应该有错误检查 range.location 不等于 NSNotFound

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

这篇关于使用offset&获取NSString中字符的索引在Objective-C中使用子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆