Difficulty trying to split a string in swift - 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

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)"

Related

How get seperated lines inside a CFString?

I want a good way for seperating lines inside a huge string. I searched and found this article:
https://medium.com/#sorenlind/three-ways-to-enumerate-the-words-in-a-string-using-swift-7da5504f0062
Base on this article I want use CFStringTokenizer. So I changed kCFStringTokenizerUnitWord to kCFStringTokenizerUnitLineBreak and finally I use this code:
func tokenize(_ str:String) -> [String] {
var inputRange = CFRangeMake(0, str.count)
var flag = UInt(kCFStringTokenizerUnitLineBreak)
var locale = CFLocaleCopyCurrent()
var tokenizer = CFStringTokenizerCreate(kCFAllocatorDefault, str as CFString, inputRange, flag, locale)
var tokenType = CFStringTokenizerAdvanceToNextToken(tokenizer)
while tokenType != []
{
var currentTokenRange = CFStringTokenizerGetCurrentTokenRange(tokenizer)
var substring = substringWithRange(str, aRange: currentTokenRange)
tokens.append(substring)
tokenType = CFStringTokenizerAdvanceToNextToken(tokenizer)
}
return tokens
}
But It return me seperated words not seperated lines. What is the problem? Or If another way(good performance) you can suggest. Thanks.

Return Function not Working When trying to convert Integer into String

import UIKit
var str = "Hello, playground"
let NumberofStopLights: Int = 4
var population: Int
population = 5000
let TownName = "HappyPlace"
let TownDescription = return "/(TownName) has a population of /(population) and /(numberofStopLights) Stop Lights
print (TownDescription)
I want to have the integers automatically go into the /(TownName), /(population) and /(numberStopLights) spaces, tried using the return function but it did not work. SO..... I tried doing this based off another post on Stack Overflow, which said to put return right in front of it but that did not work, so... what next? (Code above)
You don't need the return, also your interpolation is wrong. Should be \() instead of /() and you forgot the last " when declaring your Townname string.
var str = "Hello, playground"
let NumberofStopLights: Int = 4
var population: Int
population = 5000
let TownName = "HappyPlace"
let TownDescription = "\(TownName) has a population of \(population) and \(NumberofStopLights) Stop Lights"
print (TownDescription)
You should also try to use upper and lowercase the correct way, although the compiler doesn't care, but it will make your life a lot easier in the end!

Trim the String

Example:
abcdefgh\nbbbbbbbbb
Whenever i encounter "\n", i want to trim the string so that i can get the new string which is before "\n". The result should be abcdefgh.
How can i do that? thanks.
Try like this
import Foundation
var str = "abcdefgh\nbbbbbbbbb"
var splitStr = str.components(separatedBy: .newlines)
print(splitStr[0])
DEMO
If you want only first item
Try like this
let splitStr = str.components(separatedBy: .newlines).first
DEMO
The Swift and javascript way is to use the global split function.
var text_string = "abcdefgh\nbbbbbbbbb"
var arr = text_string.characters.split{$0 == "\n"}.map(String.init)
var need: String = arr[0]
var drop: String? = arr.count > 1 ? arr[1] : nil
print(need)

How I can take the number after the dot via substring?

I'm getting a value like this 264.8 and I want to take the value before and after the dot. I can take the value before the dot like this
var string = "264.8"
var index = string2.rangeOfString(".", options: .BackwardsSearch)?.startIndex
var substring = string.substringToIndex(index2!)
but please how I can take it after the dot?
Try this code:
var string = "264.8"
var numbers = string.componentsSeparatedByString(".")
print(numbers[0])
print(numbers[1])
var string = "264.8"
let partsArr = string.componentsSeparatedByString(".")
var beforeDot: String = partsArr[0]
var afterDot: String? = partsArr[1]
Just for the sake of completeness, an alternative is to use split:
let string = "264.8"
let result = string.characters.split(".").map { String($0) }
print(result[0]) // "264"
print(result[1]) // "8"
And another one is to use componentsSeparatedByCharactersInSet:
let string = "264.8"
let result = string.componentsSeparatedByCharactersInSet(NSCharacterSet.punctuationCharacterSet())
print(result[0]) // "264"
print(result[1]) // "8"
Alternatively, define a closure variable that handles the conversion for you
let mySubstringClosure : (String) -> (String) = { $0.componentsSeparatedByString(".").first ?? $0 }
let substring1 = mySubstringClosure("264.8") // "264"
let substring2 = mySubstringClosure("264") // "264"
let substring3 = mySubstringClosure("") // ""
Note that this code runs safely even if no dot . exists in the string, or of the string is empty.

How to append a character to a string in Swift?

This used to work in Xcode 6: Beta 5. Now I'm getting a compilation error in Beta 6.
for aCharacter: Character in aString {
var str: String = ""
var newStr: String = str.append(aCharacter) // ERROR
...
}
Error: Cannot invoke append with an argument of type Character
Update for the moving target that is Swift:
Swift no longer has a + operator that can take a String and an array of characters. (There is a string method appendContentsOf() that can be used for this purpose).
The best way of doing this now is Martin R’s answer in a comment below:
var newStr:String = str + String(aCharacter)
Original answer:
This changed in Beta 6. Check the release notes.I'm still downloading it, but try using:
var newStr:String = str + [aCharacter]
This also works
var newStr:String = str + String(aCharacter)
append append(c: Character) IS the right method but your code has two other problems.
The first is that to iterate over the characters of a string you must access the String.characters property.
The second is that the append method doesn't return anything so you should remove the newStr.
The code then looks like this:
for aCharacter : Character in aString.characters {
var str:String = ""
str.append(aCharacter)
// ... do other stuff
}
Another possible option is
var s: String = ""
var c: Character = "c"
s += "\(c)"
According to Swift 4 Documentation ,
You can append a Character value to a String variable with the String type’s append() method:
var welcome = "hello there"
let exclamationMark: Character = "!"
welcome.append(exclamationMark)
// welcome now equals "hello there!"
var stringName: String = "samontro"
var characterNameLast: Character = "n"
stringName += String(characterNameLast) // You get your name "samontron"
I had to get initials from first and last names, and join them together. Using bits and pieces of the above answers, this worked for me:
var initial: String = ""
if !givenName.isEmpty {
let char = (givenName as NSString).substring(with: NSMakeRange(0, 1))
let str = String(char)
initial.append(str)
}
if !familyName.isEmpty {
let char = (familyName as NSString).substring(with: NSMakeRange(0, 1))
let str = String(char)
initial.append(str)
}
for those looking for swift 5, you can do interpolation.
var content = "some random string"
content = "\(content)!!"
print(content) // Output: some random string!!
let original:String = "Hello"
var firstCha = original[original.startIndex...original.startIndex]
var str = "123456789"
let x = (str as NSString).substringWithRange(NSMakeRange(0, 4))
var appendString1 = "\(firstCha)\(x)" as String!
// final name
var namestr = "yogesh"
var appendString2 = "\(namestr) (\(appendString1))" as String!*