Jimmy
Jimmy

Reputation: 893

Divide NSStrings into paragraphs

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 paragraphs. Im trying:

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

but it doesn't work.

Upvotes: 3

Views: 2246

Answers (4)

Rudolf Adamkovič
Rudolf Adamkovič

Reputation: 31486

Use enumerateSubstringsInRange:options:usingBlock: with NSStringEnumerationByParagraphs.

Upvotes: 3

jrturton
jrturton

Reputation: 119242

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

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

Upvotes: 5

Zack Brown
Zack Brown

Reputation: 6028

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:@", "];

Upvotes: 0

Youssef
Youssef

Reputation: 3592

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

Upvotes: 2

Related Questions