开发者

Divide NSStrings into paragraphs

开发者 https://www.devze.com 2023-04-10 05:37 出处:网络
I obtain a plain text from a xml feed and I want to know if there\'s a possible way to split that text into p开发者_高级运维aragraphs. Im trying:

I obtain a plain text from a xml feed and I want to know if there's a possible way to split that text into p开发者_高级运维aragraphs. Im trying:

*htmlbody = [item.text stringByReplacingOccurrencesOfString:@"\n" withString:@"<br />"]; 

but it doesn't work.


NSArray *paragraphs = [item.text componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];

Gives you an array of strings (one per paragraph) for all line termination options.


Use enumerateSubstringsInRange:options:usingBlock: with NSStringEnumerationByParagraphs.


The first and most common approach is:

NSArray *arr = [myString componentsSeparatedByString:@"\n"];

This, however, ignores the fact that there are a number of other ways in which a paragraph or line break may be represented in a string—\r, \r\n, or Unicode separators.

From Apple's String Programming Guide:

    NSString *string = /* assume this exists */;
    unsigned length = [string length];
    unsigned paraStart = 0, paraEnd = 0, contentsEnd = 0;
    NSMutableArray *array = [NSMutableArray array];
    NSRange currentRange;
    while (paraEnd < length) {
        [string getParagraphStart:&paraStart end:&paraEnd
                      contentsEnd:&contentsEnd forRange:NSMakeRange(paraEnd, 0)];
        currentRange = NSMakeRange(paraStart, contentsEnd - paraStart);
        [array addObject:[string substringWithRange:currentRange]];
    }

That wil give you an array of NSString with your paragraphs


Sounds like you're on the right track. Or at least, that's certainly the approach I would try.

Perhaps your new lines contain carriage returns so try \r\n or possibly even \n\n but without the actual content you're trying to parse it's hard to discern what you should be using as a delimiter.

Have a look at the NSString documentation for componentsSeperatedByString:

NSString *list = @"Norman, Stanley, Fletcher";
NSArray *listItems = [list componentsSeparatedByString:@", "];
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号