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
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"
trim method removes any line breaks from the start and end of a string. It handles all line terminator characters (LF, CR, etc). The method also removes any leading or trailing spaces or tabs. The trim() method does not change the original string, it returns a new string.
The basic idea for your code would be replacing all double /n with a single /n.
var aString = "This is my string"
var newString = aString.replacingOccurrences(of: "\n\n", with: "\n")
what about this?
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")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With