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

发布于 2024-12-20 09:38:16 字数 442 浏览 5 评论 0原文

我有一根绳子!

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

我想要做的是:

  1. 假设字符串中的第一个字符位于索引 0 处。转到第 11 个字符(即上例中的“l”),并向后找到第一个出现的空格的位置(在上面的字符串中) ,如果我们从“l”向后移动,第一个出现的空间的位置是位置 10)。我们将此空间的索引称为“leSpace”,值为 10。
  2. 使用 ... 将剩余字符串作为新字符串的子串

    [myString substringFromIndex:leSpace]
    

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

随心而道 2024-12-27 09:38:16
- (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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文