简体   繁体   中英

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.

[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

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];
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM