如何在一行中获取 NSString 的前 40 个字符

How to get the first 40 characters of a NSString in a line

我有一个 NSString。我正在尝试获取第一行的前 40 个字符。 到目前为止,我已经做到了。

NSString *text = @"Somewhere, something incredible is waiting to be known";
text = [text substringToIndex:40];

NSLog(OUTPUT : %@, text); 
OUTPUT : Somewhere, something incredible is wait

字符串 waiting 未完成。我需要的实际输出是

REQ OUTPUT : Somewhere, something incredible is waiting

我需要前 40 个字符,但如果最后一个字不完整,则应该完成。 有人可以告诉我该怎么做吗? 提前致谢。

检查最后一个单词是否不完整的逻辑。

  1. 获取第 41 个字符并检查它是否为 spaces。
  2. 如果是,则什么都不做。
  3. 否则,获取字符串中最后一个 space 的位置(trimmed 字符串)和 trim 您的父字符串直到该位置。

如果您可以扩展超过 40 个字符来完成您的字符串,那么您将检查第 40 个字符之后的第一个 space 和 trim 您的父字符串直到该位置。

希望你能把它转换成 Obj-C

代码

 NSString *text = @"Somewhere, something incredible is waiting to be known";
__block NSInteger targetIndex = text.length;
[text enumerateSubstringsInRange:NSMakeRange(0, text.length)
                           options:NSStringEnumerationByWords
                        usingBlock:
 ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
     NSInteger lastIndex = substringRange.location + substring.length;
     if (lastIndex > 40) {
         targetIndex = lastIndex;
         *stop = true;
     }
 }];
text = [text substringToIndex:targetIndex];
NSLog(@"%@",text);

日志

Somewhere, something incredible is waiting