tudoricc
tudoricc

Reputation: 729

Difficulty trying to split a string in swift

I have an issue in swift when trying to split a bizzare string in swift

The string is:

qwerty.mapView

37.33233141 -122.0312186

tyrewq.mapView

37.33233141 -122.0312

How should I do if i try to make it look like this

qwerty.mapView 37.31 -122.031

tyrewq.mapView 37.33 -122.032

I tried some things but I hit an issue because of that starting string having a \n after each word

Upvotes: 0

Views: 135

Answers (1)

Prine
Prine

Reputation: 12538

I did some tests in a Playground. The following code should do what you want. You can write it much shorter, but for better explanation I split every command to one line..

var numberFormatter = NSNumberFormatter()
numberFormatter.maximumFractionDigits = 3 // On the number formatter you can define your desired layout

var testString = "qwerty.mapView\n37.33233141 -122.0312186"

var splitByNewLine = testString.componentsSeparatedByString("\n")
var splitBySpace = splitByNewLine[1].componentsSeparatedByString(" ")
var nsstringLongitude = NSString(string:splitBySpace[0])
var longitude = nsstringLongitude.floatValue

var nsstringLatitude = NSString(string:splitBySpace[1])
var latitude = nsstringLatitude.floatValue


var formattedLongitude = numberFormatter.stringFromNumber(longitude)
var formattedLatitude = numberFormatter.stringFromNumber(latitude)

var finalOutput = "\(splitByNewLine[0]) \(formattedLongitude) \(formattedLatitude)"

Upvotes: 1

Related Questions