objective-c 从 NSString 的第一行删除换行符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1005281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 21:44:17  来源:igfitidea点击:

Remove newline character from first line of NSString

iphoneobjective-ccocoamacosnsstring

提问by Brock Woolf

How can I remove the first \ncharacter 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.

我希望这能让它更清楚。

采纳答案by e.James

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

回答by monowerker

[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

如果它是字符串中的第一个字符,将完全按照您的要求执行并删除换行符

回答by Quinn Taylor

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 IFyou autorelease what's there first so you don't leak the memory.

如果您首先自动释放那里的内容,则上次调用方法调用的结果甚至可以安全地分配回原始内容,这样您就不会泄漏内存。