tags:

views:

69

answers:

1

Objective-C::

I want to insert the line-feed character in the specified number of characters.

Please teach when knowing.

for example

NSString str = @"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";

?????? // -> @"aaaaa\naaaaa\naaaaa\n......"
+1  A: 

No, apparently I don't have anything better to do on a Friday night than to answer random ancient "my tags" questions asked by people who were never that interested in the first place and have anyway long since departed SO.

-(NSString*)breakString:(NSString*)str everyNCharacters:(NSUInteger)n withDelimiter:(NSString*)delimiter
{
    NSUInteger numBreaks = ([str length] / n) - (([str length] % n == 0) ? 1 : 0);

    if ( numBreaks < 1 )
        return str;

    NSMutableString* result = [NSMutableString stringWithCapacity:([str length] + [delimiter length] * numBreaks)];

    for ( int i = 0; i < numBreaks; ++i )
    {
        [result appendFormat:@"%@%@", [str substringWithRange:NSMakeRange(i * n, n)], delimiter];
    }

    [result appendString:[str substringFromIndex:(n * numBreaks)]];

    return result;
}

In the specific case of the question, call thus:

NSString* answer = [arbitraryObjectContainingTheAboveMethod breakString:str everyNCharacters:5 withDelimiter:@"\n"];

Time for bed, said Zebedee.

walkytalky
You're secretly gunning for the Necromancer badge, aren't you? ;) Awesome answer nevertheless, so here's my upvote.
BoltClock