Brock Woolf
Brock Woolf

Reputation: 47302

Remove newline character from first line of NSString

How can I remove the first \n character from an NSString?

Edit: Just to clarify, what I would like to do is: If the first line of the string contains a \n character, delete it else do nothing.

ie: If the string is like this:

@"\nhello, this is the first line\nthis is the second line"

and opposed to a string that does not contain a newline in the first line:

@"hello, this is the first line\nthis is the second line."

I hope that makes it more clear.

Upvotes: 16

Views: 24100

Answers (3)

Quinn Taylor
Quinn Taylor

Reputation: 44769

Rather than creating an NSMutableString and using a few retain/release calls, you can use only the original string and simplify the code by using the following instead: (requires 10.5+)

NSRange foundRange = [original rangeOfString:@"\n"];
if (foundRange.location != NSNotFound)
    [original stringByReplacingOccurrencesOfString:@"\n"
                                        withString:@""
                                           options:0 
                                             range:foundRange];

(See -stringByReplacingOccurrencesOfString:withString:options:range: for details.)

The result of the last call method call can even be safely assigned back to original IF you autorelease what's there first so you don't leak the memory.

Upvotes: 6

monowerker
monowerker

Reputation: 2979

[string stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]]

will trim your string from any kind of newlines, if that's what you want.

[string stringByReplacingOccurrencesOfString:@"\n" withString:@"" options:0 range:NSMakeRange(0, 1)]

will do exactly what you ask and remove newline if it's the first character in the string

Upvotes: 40

James Eichele
James Eichele

Reputation: 119144

This should do the trick:

NSString * ReplaceFirstNewLine(NSString * original)
{
    NSMutableString * newString = [NSMutableString stringWithString:original];

    NSRange foundRange = [original rangeOfString:@"\n"];
    if (foundRange.location != NSNotFound)
    {
        [newString replaceCharactersInRange:foundRange
                                 withString:@""];
    }

    return [[newString retain] autorelease];
}

Upvotes: 11

Related Questions