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

Drag and launch type thing in Swift Sprite Kit?
Extend navigation bar under status bar in interface building
UIBezierPath: byRoundingCorners: doesn't work
How To Change The Title Color of an MFMailComposeViewController?
Preventing UIImagePicker memory problems
CoreData. Manage multiple coordinators, in multi thread, multi context
AVPlayer(ViewController): can not play HLS HD video
Duplicate symbols for architecture when using global constants [duplicate]
iOS: UIWebView display link from website [duplicate]
In App Purchases returns error
NSAttributedString with image doesn't work in UITextField?
How to generate iPhone simulator build or .zip file for submit in Facebook for review in iOS
Xcode lost connection with simulator iOS 9
UIView not moving when I change it's x origin in swift
Disabling iCloud backup, tmp directory and replacement of files in path
Type cast class conforming to sub-protocol to parent-protocol in Swift

Categories

HOME
redirect
lua
hortonworks-data-platform
crf
saml
runtime-error
turing
svg.js
autofac
eps
android-vision
sparkpost
editor
yii2-advanced-app
cloudrail
pyfftw
export-to-excel
libssh
jmespath
round-robin
amplitude
servlet-filters
sfsafariviewcontroller
beanstalkd
realm-java
ormlite-servicestack
shape
listbox
desktop-app-converter
meanjs
masstransit
launchpad
codewarrior
directx-12
jtapi
gridstack
gradient-descent
mask
angular-xeditable
runge-kutta
linechart
response
signing
runc
windows-scripting
amazon-vpc
uitabbarcontroller
ulimit
free-diameter
nscalendar
kendo-chart
simplesamlphp
smartbanner
jasmine2.0
paypal-webhooks
glumpy
angular-directive
graph-traversal
tastypie
asp.net-mvc-custom-filter
geneticsharp
wxhaskell
telecommunication
visual-build-professional
vlc-android
dms
restbed
main-activity
jni4net
membership
ssha
thinktecture-ident-server
post-processor
user-registration
antiforgerytoken
lossless-compression
janino
java-client
android-design-library
tab-delimited
concurrentdictionary
custom-titlebar
bson
serverside-javascript
blazeds
delphi-2009
libavcodec
execcommand
apache-commons-dbcp
globbing
hogan.js
hudson-plugins
gigaspaces
clean-urls
51degrees
oledbcommand
graphiti-js
j#
junitperf
nntp
system-tray
help-authoring
roguelike

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