ios 使用偏移量获取 NSString 中字符的索引并在 Objective-C 中使用子字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8418184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 15:46:43  来源:igfitidea点击:

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

objective-ciosnsstringsubstringnsrange

提问by Umair Khan Jadoon

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]
    
  1. 假设字符串中的第一个字符在索引0处,转到第11个字符(即上例中的'l'),向后找到第一个出现空格的位置(在上面的字符串中,第一个出现空格的位置如果我们从 'l' 向后走,则在位置 10)。让我们将此空间的索引称为“leSpace”,其值为 10。
  2. 使用 ...

    [myString substringFromIndex:leSpace]
    

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

......我希望我已经解释得很好。请帮忙,你能写一个片段或其他东西来帮助我完成这项任务吗?

回答by zaph

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

For the options use: NSBackwardsSearch

对于选项使用: 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:

NSLog 输出:

range.location: 10
substring: 'lovely string'

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

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