10

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"
luke
  • 2,743
  • 4
  • 19
  • 43
  • What have you tried? Have you looked at replacing the `/n/n` with just `/n` http://stackoverflow.com/questions/24200888/any-way-to-replace-characters-on-swift-string or even `/n/n ` with `/n` to get rid of the additional space. Though that might be a bit simplistic – Flexicoder Mar 28 '17 at 15:06
  • 1
    http://stackoverflow.com/questions/28957940/remove-all-line-breaks-at-the-beginning-of-a-string-in-swift – Tushar Sharma Mar 28 '17 at 15:06
  • Are you sure it's not `\n`? – Sulthan Mar 28 '17 at 15:15
  • @Sulthan yeah sorry it is \n – luke Mar 28 '17 at 15:15

3 Answers3

15

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")
palsch
  • 5,528
  • 4
  • 21
  • 32
Hienz
  • 688
  • 7
  • 21
  • I was going to say the same thing but you beat me to it. – Duncan C Mar 28 '17 at 15:08
  • problem is, `\n` still sits at the end of the string if there is an `\n` there, so I get an extra empty line at the end of the string when displaying inside the textview – luke Mar 28 '17 at 15:12
  • 1
    I mistyped. Replace the /n parts of my code with \n. It should work, no way it doesn't. – Hienz Mar 28 '17 at 15:18
  • It does work but only to an extent - lets say the string is `"This is a string \n\n\n"` - it will return `"This is a string \n\n"`. Also, if the \n sits at the end of a string, i want it removed. – luke Mar 28 '17 at 15:24
  • You'll need to have the code in a loop, which runs until \n\n can be found in your string. – Hienz Mar 28 '17 at 15:28
10

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")
}
André Slotta
  • 13,774
  • 2
  • 22
  • 34
0

Try this

var aString = "This is a string \n\n This is the second line of the string\n\n"

let components = aString.components(separatedBy: "\n\n").filter { $0 != "" }
print(components.joined(separator: "\n"))

// prints expected output with a single line separator
David
  • 2,109
  • 1
  • 22
  • 27