ios 从 NSString 中删除换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1807803/
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
Removing new line characters from NSString
提问by y ramesh rao
I have a NSString
like this:
我有一个NSString
这样的:
Hello
World
of
Twitter
Lets See this
>
I want to transform it to:
我想将其转换为:
Hello World of Twitter Lets See this >
你好推特世界让我们看看这个 >
How can I do this? I'm using Objective-C on an iPhone.
我怎样才能做到这一点?我在 iPhone 上使用 Objective-C。
回答by hallski
Split the string into components and join them by space:
将字符串拆分为组件并按空格连接它们:
NSString *newString = [[myString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:@" "];
回答by imnk
Splitting the string into components and rejoining them is a very long-winded way to do this. I too use the same method Paul mentioned. You can replace any string occurrences. Further to what Paul said you can replace new line characters with spaces like this:
将字符串拆分为组件并重新连接它们是一种非常冗长的方法。我也使用保罗提到的相同方法。您可以替换任何出现的字符串。除了保罗所说的,你可以用这样的空格替换换行符:
myString = [myString stringByReplacingOccurrencesOfString:@"\n" withString:@" "];
回答by Paul Peelen
I'm using
我正在使用
[...]
myString = [myString stringByReplacingOccurrencesOfString:@"\n\n" withString:@"\n"];
[...]
/Paul
/保罗
回答by Kjuly
My case also contains \r
, including \n
, [NSCharacterSet newlineCharacterSet]
does not work, instead, by using
我的案例还包含\r
,包括\n
,[NSCharacterSet newlineCharacterSet]
不起作用,而是通过使用
htmlContent = [htmlContent stringByReplacingOccurrencesOfString:@"[\r\n]"
withString:@""
options:NSRegularExpressionSearch
range:NSMakeRange(0, htmlContent.length)];
solved my problem.
解决了我的问题。
Btw, \\s
will remove all white spaces, which is not expected.
顺便说一句,\\s
将删除所有空白,这是意料之中的。
回答by Michael Shang
Providing a Swift 3.0 version of @hallski 's answer here:
在此处提供@hallski 答案的 Swift 3.0 版本:
self.content = self.content.components(separatedBy: CharacterSet.newlines).joined(separator: " ")
Providing a Swift 3.0 version of @Kjuly 's answer here (Note it replaces any number of new lines with just one \n. I would prefer to not use regular express if someone can point me a better way):
在此处提供@Kjuly 答案的 Swift 3.0 版本(请注意,它仅用一个 \n 替换了任意数量的新行。如果有人能指出我更好的方法,我宁愿不使用正则表达式):
self.content = self.content.replacingOccurrences(of: "[\r\n]+", with: "\n", options: .regularExpression, range: Range(uncheckedBounds: (lower: self.content.startIndex, upper: self.content.endIndex)));