从字符串中删除换行符 [英] Removing line breaks from string
本文介绍了从字符串中删除换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的字符串:
I have a string like so:
var aString = "This is a string \n\n This is the second line of the string\n\n"
里面的文本视图看起来像这样:
Which inside a textview looks like so:
This is a string
This is the second line of the string
// 2 extra lines of unnecessary white space
但是我希望它看起来像这样:
But i want it to look like this:
This is a string
This is the second line of the string
我想从字符串的末尾删除所有"\ n",并在重复的位置删除\ n,以使中间没有空格.
I want to remove all "\n" from the end of the string and remove \n where it repeats itself so theres no white space in the middle.
理想情况下,我猜最终结果应该是这样:
ideally, I'm guessing the end result should be this:
var aString = "This is a string \n This is the second line of the string"
推荐答案
这是什么?
var aString = "This is a string \n\n\n This is the second line of the string\n\n"
// trim the string
aString.trimmingCharacters(in: CharacterSet.newlines)
// replace occurences within the string
while let rangeToReplace = aString.range(of: "\n\n") {
aString.replaceSubrange(rangeToReplace, with: "\n")
}
这篇关于从字符串中删除换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文