Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing line breaks from string

Tags:

ios

swift

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"
like image 350
luke Avatar asked Mar 28 '17 15:03

luke


People also ask

Does trim remove line breaks?

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.


2 Answers

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")
like image 169
Hienz Avatar answered Oct 22 '22 03:10

Hienz


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")
}
like image 9
André Slotta Avatar answered Oct 22 '22 03:10

André Slotta