ios


How should I remove all the empty lines from a string


I get a string value from an api, and there's a lot of useless empty lines:
bla bla bla
bla
bla bla bla
I want to remove those empty lines to get this result:
bla bla bla
bla
bla bla bla
How can I proceed ?
You can use String enumerateLines method and filter the empty elements. Then you just need to use joinWithSeparator \n to concatenate your string again:
let linesString = "bla bla bla\n\n\nbla\nbla bla bla\n"
var linesArray: [String] = []
linesString.enumerateLines { line, _ in linesArray.append(line) }
let result = linesArray.filter{!$0.isEmpty}.joinWithSeparator("\n")
print(result) // "bla bla bla\nbla\nbla bla bla"
Here's an easy way to do it:
import Foundation
let string = "bla bla bla\n\n\nbla\n\nbla bla bla\n"
var filtered = ""
string.enumerateLines({if !$0.line.isEmpty { filtered.appendContentsOf("\($0.line)\n") }})
print(filtered)
// => bla bla bla
// => bla
// => bla bla bla
Another way without creating a mutable variable:
let newString = string.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()).filter({!$0.isEmpty}).joinWithSeparator("\n")
MuhammadRaheelMateen's and AtheistP3ace's suggestions are headed in the right direction, but whitespaceCharacterSet‌ would also remove spaces in between words. You should only remove newlineCharacterSet.
But even then, "trimming" would only remove the whitespace at the ends; and as Suthan said, you only want to remove duplicate new lines.
Try separating the string into components separated by newlines, filtering out "", then rejoining with a newline:
let string = blaString.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()).filter(){$0 != ""}.joinWithSeparator("\n")

Related Links

libobjc.A.dylib objc_msgSend crash occurring with core data usage in background thread
Disabling Dynamic Type in Swift
how to make overlay with activity indicator programatically
performseguewithidentifier works with a delay
Type [TeamModel] has no subscript members
Pdf file in webview not scrolling
Ternary Conditional Operator for nil/not nil
Xamarin / IOS / Azure - No 'id' member found on type
iOS 9 core location crash
Better accessibility label for a clickable table view cell
iOS add fixed footer UIView to multiscreen app
how to send data from iOS prototype cell to watch with swift 2.2
What does this Google Maps iOS SDK code in Swift do?
Firebase + Swift: Unable to delete rows in tableView
AVfoundation blur background in Video
How to play music in background in Swift with MPMediaPickerController chosen songs?

Categories

HOME
bootstrap-4
angular2-forms
openshift-origin
bolt-cms
jsonschema
datetime
weight
chronicle
encog
geany
google-adwords
wget
windows-10-desktop
proftpd
condor
apex
message
python-2.5
imp
records
py4j
cadvisor
precision
epicorerp
physics
angular-ngmodel
f2py
codewarrior
coqide
django-users
azure-api-apps
swipe
kube-dns
dokuwiki
cloudinary
lifecycle
jformattedtextfield
sieve-of-eratosthenes
executorservice
p4-lang
argparse
disqus
flags
weebly
brainfuck
project-centennial
tabview
docker-swarm-mode
azure-cdn
scoring
sql-mode
ctl
complement
ammonite
typesetting
dwr
getelementbyid
singlepage
zenity
wxhaskell
bootstrap-slider
building
submission
securesocial
bash-completion
vimeo-ios
pddl
administrator
egl
python-dragonfly
sample-data
android-gpuimageview
axlsx
chunk-templates
keypad
sigkill
gcovr
computer-science-theory
jasmin
android-menu
publish-actions
ash
asp.net-apicontroller
youtrack-api
validform
nawk
mod-python
sysadmin
nsusernotificationcenter
kmz
progressdialog
hudson-plugins
timespan
mixing
arr
livevalidation
springboard
openfeint
jtemplates
plinqo
codi
cracker
crc-cards

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App