如何在iOS中以段落顺序获取NSString中的所有段落?

时间:2014-09-17 10:19:06

标签: ios objective-c nsstring nsparagraphstyle

我从这样的API中获取字符串

  New version of WhatsApp Messenger is
  now available.
  JANUARY 12, 2013
  Your upgrade will bring improvements, larger
  group chats and new features such as
  Profile Photos!

有没有办法从上面的字符串中获取段落?

我使用了NSArray *paragraphs = [result componentsSeparatedByString:@"\n"];

根据我的要求,它应该有3个字符串

 paragraphs=   {
          "New version of WhatsApp Messenger is now available."
          "JANUARY 12, 2013"
          "Your upgrade will bring improvements, larger  group chats and new features such as Profile Photos!"

    }

但它的回归

paragraphs= {
      "New version of WhatsApp Messenger is"
      "now available."
      "JANUARY 12, 2013"
      "Your upgrade will bring improvements, larger"
      "group chats and new features such as"
      "Profile Photos!"
 }  

3 个答案:

答案 0 :(得分:0)

你可以试试这个:

    NSArray* newLinestring = [result componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];

    NSMutableArray *newLinesArray = [NSMutableArray array];

   [result enumerateSubstringsInRange:NSMakeRange(0, result.length) options:NSStringEnumerationByParagraphs usingBlock:^(NSString *substring, NSRangesubstringRange, NSRange enclosingRange, BOOL *stop) {
  // ADD TO AN ARRAY HERE THE SUBSTRINGS
 }];

答案 1 :(得分:0)

据我所知,输出是正确的,因为有5个换行符。输入不是你想要的。你的意见应该是:

New version of WhatsApp Messenger is now available.
JANUARY 12, 2013
Your upgrade will bring improvements, larger group chats and new features such as Profile Photos!

答案 2 :(得分:0)

这是你的问题的黑客

1检查所有换行符。

2删除特定范围内的换行符。

3.done

1.  int count = 0;
    for (unsigned int i=0; i < [result length]; ++i) {
        if ([result characterAtIndex:i] == '\n') {
            NSLog(@"index %i",i);
            ++count;

        }
    }

2.  

    NSRange first = {36, 1};
    NSRange fourth= {113,1};
    NSRange fifth={150,1};
    NSString *stringWithSpaces;

    stringWithSpaces = [result stringByReplacingCharactersInRange:first withString:@" "];
    result=stringWithSpaces;
    stringWithSpaces = [result stringByReplacingCharactersInRange:fourth withString:@" "];
    result=stringWithSpaces;
    stringWithSpaces = [result stringByReplacingCharactersInRange:fifth withString:@" "];
    result=stringWithSpaces;

     NSArray *paragraphs = [result componentsSeparatedByString:@"\n"];
     NSLog(@"Paragraph=%@",paragraphs);
  1. 完成。

    快乐编码