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

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.

Related

Swift - search entire struct for string

To search for a string included in a struct I use:
let results = myArray.filter( {$0.model.localizedCaseInsensitiveContains("bu")} )
But say the struct has several properties that I'd like to search - or maybe I'd even like to search all of them at one time. I can only filter primitive types so leaving 'model' out won't work.
Solution -------------------------
While I really liked the idea of using key paths as Matt suggested below, I ended up adding a function to my struct that made my view controller code much cleaner:
struct QuoteItem {
var itemIdentifier: UUID
var quoteNumber: String
var customerName: String
var address1: String
func quoteItemContains(_ searchString: String) -> Bool {
if self.address1.localizedCaseInsensitiveContains(searchString) ||
self.customerName.localizedCaseInsensitiveContains(searchString) ||
self.quoteNumber.localizedCaseInsensitiveContains(searchString)
{
return true
}
return false
}
Then, in my controller, quotes is an array of QuoteItem that I can search by simply writing:
searchQuoteArray = quotes.filter({ $0.quoteItemContains(searchString) })
This sounds like a job for Swift key paths. Just supply the key paths for the String properties you want to search.
struct MyStruct {
let manny = "Hi"
let moe = "Hey"
let jack = "Howdy"
}
let paths = [\MyStruct.manny, \MyStruct.moe, \MyStruct.jack]
let s = MyStruct()
let target = "y"
let results = paths.map { s[keyPath:$0].localizedCaseInsensitiveContains(target) }
// [false, true, true]
I hope i understood you correct. I think with this piece of code you can achieve what you want:
struct ExampleStruct {
let firstSearchString: String
let secondSearchString: String
}
let exampleOne = ExampleStruct(firstSearchString: "Hello", secondSearchString: "Dude")
let exampleTwo = ExampleStruct(firstSearchString: "Bye", secondSearchString: "Boy")
let exampleArray = [exampleOne, exampleTwo]
let searchString = "Hello"
let filteredArray = exampleArray.filter { (example) -> Bool in
// check here the properties you want to check
if (example.firstSearchString.localizedCaseInsensitiveContains(searchString) || example.secondSearchString.localizedCaseInsensitiveContains(searchString)) {
return true
}
return false
}
for example in filteredArray {
print(example)
}
This prints the following in Playgrounds:
ExampleStruct(firstSearchString: "Hello", secondSearchString: "Dude")
Let me know if it helps.

Display of special characters \u{n}

Impossible to find the solution ; it does not work...
I've been on this for hours... A little help will give me the opportunity to sleep without a nightmare...
Where is the error ?
let num: Int = 128150 // smiley = "\u{1F496}" => 128150
var str: String = String(num, radix: 16)
str = str.uppercased()
var wkHex: String = "\\u{"+str+"}" // wkHex = "\u{"+str+"}" not match
wkHex.characters.removeFirst(0) // remove "\" unnecessary at startIndex
let cnt = wkHex.characters.count
let zzz: Array = Array(wkHex.characters)
var car: String = ""
for i in 0...cnt - 1 {
car.append(zzz[i])
}
outputChar.stringValue = car // outputChar is a Label (NSTextField)
// output : \u{1F496} ! instead of : 💖
So the idea is to go from a code point to a character?
let iii = 128150
let char = Character(UnicodeScalar(iii)!)
print(char) // 💖
Swift only allows you to use the \u{...} syntax at compile time. This means that the string won't be turned into the emoji at runtime, when the value of num is known.
To do this, you can use UnicodeScalar:
let unicode = UnicodeScalar(128150)
unicode?.description // 💖

How to get the first characters in a string? (Swift 3)

I want to get a substring out of a string which starts with either "<ONLINE>" or "<OFFLINE>" (which should become my substring). When I try to create a Range object, I can easily access the the first character by using startIndex but how do I get the index of the closing bracket of my substring which will be either the 8th or 9th character of the full string?
UPDATE:
A simple example:
let onlineString:String = "<ONLINE> Message with online tag!"
let substring:String = // Get the "<ONLINE> " part from my string?
let onlineStringWithoutTag:String = onlineString.replaceOccurances(of: substring, with: "")
// What I should get as the result: "Message with online tag!"
So basically, the question is: what do I do for substring?
let name = "Ajay"
// Use following line to extract first chracter(In String format)
print(name.characters.first?.description ?? "");
// Output : "A"
If you did not want to use range
let onlineString:String = "<ONLINE> Message with online tag!"
let substring:String = onlineString.components(separatedBy: " ")[0]
print(substring) // <ONLINE>
The correct way would be to use indexes as following:
let string = "123 456"
let firstCharIndex = string.index(string.startIndex, offsetBy: 1)
let firstChar = string.substring(to: firstCharIndex)
print(firstChar)
This Code provides you the first character of the string.
Swift provides this method which returns character? you have to wrap it before use
let str = "FirstCharacter"
print(str.first!)
Similar to OOPer's:
let string = "<ONLINE>"
let closingTag = CharacterSet(charactersIn: ">")
if let closingTagIndex = string.rangeOfCharacter(from: closingTag) {
let mySubstring = string.substring(with: string.startIndex..<closingTagIndex.upperBound)
}
Or with regex:
let string = "<ONLINE>jhkjhkh>"
if let range = string.range(of: "<[A-Z]+>", options: .regularExpression) {
let mySubstring = string.substring(with: range)
}
This code be some help for your purpose:
let myString = "<ONLINE>abc"
if let rangeOfClosingAngleBracket = myString.range(of: ">") {
let substring = myString.substring(to: rangeOfClosingAngleBracket.upperBound)
print(substring) //-><ONLINE>
}
Swift 4
let firstCharIndex = oneGivenName.index(oneGivenName.startIndex, offsetBy: 1)
let firstChar = String(oneGivenName[..<firstCharIndex])
let character = MyString.first
it's an simple way to get first character from string in swift.
In swift 5
let someString = "Stackoverflow"
let firstChar = someString.first?.description ?? ""
print(firstChar)
Swift 5 extension
extension String {
var firstCharactor: String? {
guard self.count > 0 else {
return nil
}
return String(self.prefix(1))
}
}

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!*

How do you add an attribute to an Unicode string in Swift?

How do you add attribute to a UNICODE string in Swift?
NSMakeRange seems to expect String in bytes for a variable byte length UNICODE string.
Any way to solve this? Thanks in advance.
var s:NSMutableAttributedString = NSMutableAttributedString(string: "வாங்க வாங்க வணக்கமுங்க")
s.string[0...2]
s.addAttribute(NSForegroundColorAttributeName, value:UIColor(red:0.0, green:1.0, blue:0.0, alpha:1.0), range:NSMakeRange(0,3))
UPDATED EXAMPLE:
let text = "வாங்க வாங்க வணக்கமுங்க"
var startOfWord = advance(text.startIndex, 4)
var endOfWord = advance(startOfWord, 3)
var highlightRange = startOfWord..<endOfWord
text[startOfWord..<endOfWord]
let attrText = NSMutableAttributedString(string:text)
attrText.addAttribute(NSForegroundColorAttributeName, value:UIColor(red:0.0, green:1.0, blue:0.0, alpha:1.0), range:highlightRange)
How do construct NSRange from swift Range?
I created a small extension for String which works for both Index based and Int based Ranges.
extension String {
func NSRangeFromRange(swiftRange: Range<Index>) -> NSRange {
let start = swiftRange.startIndex.samePositionIn(utf16)
let end = swiftRange.endIndex.samePositionIn(utf16)
return NSRange(location: utf16.startIndex.distanceTo(start), length: start.distanceTo(end))
}
func NSRangeFromRange(swiftRange: Range<Int>) -> NSRange {
let indexRange = Range(start: startIndex.advancedBy(swiftRange.startIndex), end: startIndex.advancedBy(swiftRange.endIndex))
return NSRangeFromRange(indexRange)
}
}
Note: The function is on the String class because we need the strings UTF16View to convert between the Unicode-aware Range<Index> and the non-Unicode-aware NSRange.
I hope the below function may help you
func findAndAddAttributeString(str: String, query : String) {
let strASNSString = str as NSString
println("employeeIdAsNSString, \(strASNSString)")
var attributeDictionary = NSMutableDictionary(objects: [UIColor.grayColor(), UIFont.systemFontOfSize(17)], forKeys: [NSForegroundColorAttributeName, NSFontAttributeName])
println("attributeDictionary, \(attributeDictionary)")
var attributedEmployeeId = NSMutableAttributedString(string: strASNSString, attributes: attributeDictionary)
println("attributedEmployeeId = \(attributedEmployeeId)")
var error:NSError?
var regex = NSRegularExpression.regularExpressionWithPattern(query, options: NSRegularExpressionOptions.CaseInsensitive, error: &error)
println("regex = \(regex)")
var range = NSMakeRange(0, strASNSString.length)
println("range = \(range)")
regex.enumerateMatchesInString(strASNSString, options: nil, range: range, usingBlock:{ (textCheckingResult, MatchingFlags, unsafePointer) in
println("textCheckingResult \(textCheckingResult.rangeAtIndex(0))")
var subStringRange = textCheckingResult.rangeAtIndex(0)
attributedEmployeeId.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: subStringRange)
})
}
You can convert a swift String to Swift NSString by
var strAsNSString = "வாங்க வாங்க வணக்கமுங்க" as NSString
And then you can create NSMutableAttributedString.
Something like this might work:
let text = "வாங்க வாங்க வணக்கமுங்க"
var startOfWord = advance(text.startIndex, 5)
var endOfWord = advance(startOfWord, 5)
var range = startOfWord..<endOfWord
Even if some more work is required to figure out how far to advance (if you are looking for just one known word you can directly get it with NSRangeFromString)