Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 852
Brock Woolf Avatar asked Jun 17 '09 05:06

Brock Woolf


3 Answers

[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

like image 80
monowerker Avatar answered Nov 12 '22 02:11

monowerker


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];
}
like image 44
e.James Avatar answered Nov 12 '22 02:11

e.James


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.

like image 45
Quinn Taylor Avatar answered Nov 12 '22 03:11

Quinn Taylor