简体   繁体   English

从 NSString 的第一行删除换行符

[英]Remove newline character from first line of NSString

How can I remove the first \n character from an NSString?如何从 NSString 中删除第一个\n字符?

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.编辑:澄清一下,我想做的是:如果字符串的第一行包含一个 \n 字符,则将其删除,否则什么都不做。

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+)与其创建 NSMutableString 并使用一些保留/释放调用,不如仅使用原始字符串并使用以下代码简化代码:(需要 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.) (有关详细信息,请参阅-stringByReplacingOccurrencesOfString:withString:options:range:

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.最后一次调用方法调用的结果甚至可以安全地分配回原始IF你自动释放那里的内容,这样你就不会泄漏 memory。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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