Bro*_*olf 16 iphone macos cocoa objective-c nsstring
如何从NSString中删除第一个\n字符?
编辑:只是为了澄清,我想要做的是:如果字符串的第一行包含\n字符,删除它否则什么都不做.
ie:如果字符串是这样的:
@"\nhello, this is the first line\nthis is the second line"
Run Code Online (Sandbox Code Playgroud)
并且与第一行中不包含换行符的字符串相反:
@"hello, this is the first line\nthis is the second line."
Run Code Online (Sandbox Code Playgroud)
我希望这更清楚.
mon*_*ker 39
[string stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]]
Run Code Online (Sandbox Code Playgroud)
如果这是你想要的,将从任何类型的换行符修剪你的字符串.
[string stringByReplacingOccurrencesOfString:@"\n" withString:@"" options:0 range:NSMakeRange(0, 1)]
Run Code Online (Sandbox Code Playgroud)
如果它是字符串中的第一个字符,它将完全按照您的要求执行并删除换行符
e.J*_*mes 11
这应该做的伎俩:
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];
}
Run Code Online (Sandbox Code Playgroud)
不是创建NSMutableString并使用一些保留/释放调用,而是只使用原始字符串并通过使用以下代码简化代码:(需要10.5+)
NSRange foundRange = [original rangeOfString:@"\n"];
if (foundRange.location != NSNotFound)
[original stringByReplacingOccurrencesOfString:@"\n"
withString:@""
options:0
range:foundRange];
Run Code Online (Sandbox Code Playgroud)
(详见-stringByReplacingOccurrencesOfString:withString:options:range:.)
最后一次调用方法调用的结果甚至可以安全地分配回原始IF如果您首先自动释放那些内容,那么您不会泄漏内存.
| 归档时间: |
|
| 查看次数: |
23908 次 |
| 最近记录: |