how to split a string like char and number separately in swift - ios

i am facing one issue about how to split a number and string in same String and display it. To be very clear lets take an example i have an string like,
myString = "MH04ED7897"
i want to my output like this
outPut = MH-04-ED-7897

I am new in Swift. try this
let startIndex = number.startIndex.advancedBy(4)
let lastStr:String = number.substringFromIndex(startIndex)
let InitialStr:String = number.substringToIndex(startIndex)
NSLog("%# %#", lastStr,InitialStr)
let startInitialIndex = InitialStr.startIndex.advancedBy(2)
let InitialStart:String = InitialStr.substringToIndex(startInitialIndex)
let Initialfinish:String = InitialStr.substringFromIndex(startInitialIndex)
print("initalStart :\(InitialStart)")
print("Initialfinish :\(Initialfinish)")
let startlastIndex = lastStr.endIndex.advancedBy(-4)
let lastStart:String = lastStr.substringFromIndex(startlastIndex)
let replaced = lastStr.stringByReplacingOccurrencesOfString(lastStart, withString: "")
print("replace:\(replaced)")
// let lastFinish:String = lastStr.substringToIndex(startfirstIndex)
print("lastStart :\(lastStart)")
you get output like

Related

Remove special characters from the string

I am trying to use an iOS app to dial a number. The problem is that the number is in the following format:
po placeAnnotation.mapItem.phoneNumber!
"‎+1 (832) 831-6486"
I want to get rid of some special characters and I want the following:
832-831-6486
I used the following code but it did not remove anything:
let charactersToRemove = CharacterSet(charactersIn: "()+-")
var telephone = placeAnnotation.mapItem.phoneNumber?.trimmingCharacters(in: charactersToRemove)
Any ideas?
placeAnnotation.mapItem.phoneNumber!.components(separatedBy: CharacterSet.decimalDigits.inverted)
.joined()
Here you go!
I tested and works well.
If you want something similar to CharacterSet with some flexibility, this should work:
let phoneNumber = "1 (832) 831-6486"
let charsToRemove: Set<Character> = Set("()+-".characters)
let newNumberCharacters = String(phoneNumber.characters.filter { !charsToRemove.contains($0) })
print(newNumberCharacters) //prints 1 832 8316486
I know the question is already answered, but to format phone numbers in any way one could use a custom formatter like below
class PhoneNumberFormatter:Formatter
{
var numberFormat:String = "(###) ### ####"
override func string(for obj: Any?) -> String? {
if let number = obj as? NSNumber
{
var input = number as Int64
var output = numberFormat
while output.characters.contains("#")
{
if let range = output.range(of: "#", options: .backwards)
{
output = output.replacingCharacters(in: range, with: "\(input % 10)")
input /= 10
}
else
{
output.replacingOccurrences(of: "#", with: "")
}
}
return output
}
return nil
}
func string(from number:NSNumber) -> String?
{
return string(for: number)
}
}
let phoneNumberFormatter = PhoneNumberFormatter()
//Digits will be filled backwards in place of hashes. It is easy change the custom formatter in anyway
phoneNumberFormatter.numberFormat = "###-##-##-##-##"
phoneNumberFormatter.string(from: 18063783889)
Swift 3
func removeSpecialCharsFromString(_ str: String) -> String {
struct Constants {
static let validChars = Set("1234567890-".characters)
}
return String(str.characters.filter { Constants.validChars.contains($0) })
}
To Use
let str : String = "+1 (832) 831-6486"
let newStr : String = self.removeSpecialCharsFromString(str)
print(newStr)
Note: you can add validChars which you want in string after operation perform.
If you have the number and special character in String format the use following code to remove special character
let numberWithSpecialChar = "1800-180-0000"
let actulNumber = numberWithSpecialChar.components(separatedBy: CharcterSet.decimalDigit.inverted).joined()
Otherwise, If you have the characters and special character in String format the use following code to remove special character
let charactersWithSpecialChar = "A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal-Panama!"
let actulString = charactersWithSpecialChar.components(separatedBy: CharacterSet.letters.inverted).joined(separator: " ")
NSString *str = #"(123)-456-7890";
NSLog(#"String: %#", str);
// Create character set with specified characters
NSMutableCharacterSet *characterSet =
[NSMutableCharacterSet characterSetWithCharactersInString:#"()-"];
// Build array of components using specified characters as separtors
NSArray *arrayOfComponents = [str componentsSeparatedByCharactersInSet:characterSet];
// Create string from the array components
NSString *strOutput = [arrayOfComponents componentsJoinedByString:#""];
NSLog(#"New string: %#", strOutput);

How to solve iOS error with locale decimal point / comma in calculations? (with NumberFormatter)

I have the following problem with iOS calculations when the user is in different locales. Here in Europe the decimal point separator is a "," and in other locales it might be a ".". As long as the user is in a locale with a "." all calculations work fine, but when a comma is used instead I get an error. Here's the simple code so far:
if let expense = expenseTextField.text
let expenseValue = Double(expense)
let guests = guestTextField.text
let guestValue = Double(guests) {
let result = round((expenseValue / guestValue) * 100) / 100
resultLabel.text = priceString
//resultLabel.text = String(result)
} else {
resultLabel.text = "No values!"
}
I am pretty sure I have to use the numberFormatter as far as I understand other questions on here, but I don't get how to do this and the documentation doesn't provide a sample how to create a double or float from a string. I tried the following but I get an error stating that I cannot neither create doubles nor use these variables for calculations:
if let expense = expenseTextField.text
let expenseValue = String(expense),
let guests = guestTextField.text
let guestValue = String(guests) {
let expenseFormatter = NumberFormatter()
expenseFormatter.number(from: expenseValue)
let guestFormatter = NumberFormatter()
guestFormatter.number(from: guestValue)
let expenseDouble = Double(expenseFormatter)
let guestDouble = Double(guestFormatter)
let result = round((expenseDouble / guestDouble) * 100) / 100
resultLabel.text = priceString
} else {
resultLabel.text = "No values!"
}
I am not sure how to create real Doubles from those strings with numberFormatter and then use them in calculations.
Can someone give me a tip?
Thanks
The only thing you need is to write the method call correctly:
let expenseDouble = expenseFormatter.number(from: expenseValue)?.doubleValue ?? 0
let guestDouble = guestFormatter.number(from: guestValue)?.doubleValue ?? 0
A formatter/parser directly converts string to number. You then have to take the Double value from it. Note that parsing can fail and you have to solve the resulting optional in that case, e.g. using ?? 0.

How can i parse MIDIRawData (SysEx) out of a midiEvent in Swift 3? (under iOS)

i have big trouble parsing MIDIRawData (SysEx Data) out of a midi-event of a MusicTrack (XCode8.1, iOS10.1)
I managed to parse MidiNoteMessages and MidiChannelMessages with the following code (Swift3):
(eventType and eventData was extracted with MusicEventIteratorGetEventInfo…)
switch eventType {
case kMusicEventType_MIDINoteMessage:
let temp = eventData?.bindMemory(to: MIDINoteMessage.self, capacity: 5)
let channel = temp!.pointee.channel
let note = temp!.pointee.note
let vel = temp!.pointee.velocity
let relVel = temp!.pointee.releaseVelocity
let duration = temp!.pointee.duration
case kMusicEventType_MIDIChannelMessage:
let temp = eventData?.bindMemory(to: MIDIChannelMessage.self, capacity: 4)
let status = temp!.pointee.status & 0b11110000
let channel = temp!.pointee.status & 0b0000111
let data1 = temp!.pointee.data1
let data2 = temp!.pointee.data2
let reserved = temp!.pointee.reserved
In the following case i get the right length of the data, but data itself just consists of the first entry of the SysEx Message
case kMusicEventType_MIDIRawData:
debug.printDebugText(text: "kMusicEventType_MIDIRawData", ToConsole: debugViewGlobal)
let raw = eventData?.bindMemory(to: MIDIRawData.self, capacity: 2)
let length = raw!.pointee.length
let data = raw!.pointee.data // (should be of Type (UInt8)… but is just one UInt8 Value
How can i get the rest of the SysEs Message ?
How do i have to handle (UInt8) ?
Thank You,
Sebastian

How to get data from string after particular backslash?

I have a string such as \home\var\path\uplaod\abc.png. Now I want to get data from uplaod onwards. Please suggest any function or code?
If path of image is not fixed or order of uplaod is not specific try like this.
let string = "\\home\\var\\path\\uplaod\\abc.png"
if let range = string.range(of: "uplaod") {
let imagePath = string.substring(from: range.lowerBound)
print(imagePath)
}
Output
uplaod\abc.png
let string = "\\home\\var\\path\\uplaod\\abc.png"
let parts = string.components(separatedBy: "\\")
parts // ["", "home", "var", "path", "uplaod", "abc.png"]
Any of the elements of this array you can get by its index.
parts[4..<parts.count].joined(separator: "\\") // "uplaod\\abc.png"

StringBetweenString function

I need to get substring between two strings from my text. For example, I have text "http://google.com" and I want to get substring between "://" and ".".
I don't know, how I can do that.
I try to use regular expressions, but I think, it's bad way.
A couple of options:
Regular expressions work well. See ICU User Guide: Regular Expressions
Example:
let us = "http://google.com"
let range = us.rangeOfString("(?<=://)[^.]+(?=.)", options:.RegularExpressionSearch)
if range != nil {
let found = us.substringWithRange(range!)
println("found: \(found)") // found: google
}
Notes:
(?<=://) means preceded by ://
[^.]+ means any characters except .
(?=.) means followed by .
NSScanner is also a good method. See Apple's NSScanner Class Reference
Example:
let us = "http://google.com"
let scanner = NSScanner(string:us)
var scanned: NSString?
if scanner.scanUpToString("://", intoString:nil) {
scanner.scanString("://", intoString:nil)
if scanner.scanUpToString(".", intoString:&scanned) {
let result: String = scanned as String
println("result: \(result)") // result: google
}
}
You can use the regular Expression
://.+.
it matches to
://google.
in this code:
var yourURL: NSString = "http://google.com" // this is your input and could be any URL
var regex: NSRegularExpression = NSRegularExpression.regularExpressionWithPattern("://.+\\.", options: NSRegularExpressionOptions.fromMask(UInt(0)), error: nil) // need double backspace because of backspace in String is \\ not \
var needleRange = regex.rangeOfFirstMatchInString(yourURL, options:NSMatchingOptions.Anchored, range: NSMakeRange(0, yourURL.length))
var needle: NSString = yourURL.substringWithRange(needleRange)
Now you can remove the first 3 symbols and the last one and you got
google
with this code:
import Foundation
var halfURL: NSString = "://google."
var prefix: NSString = "://"
var suffix: NSString = "."
var needleRange: NSRange = NSMakeRange(prefix.length, halfURL.length - prefix.length - suffix.length)
var needle: NSString = halfURL.substringWithRange(needleRange)
// needle is now 'google'
If your input is a valid URL, you can take advantage of the NSURL class to do the parsing for you:
var result : NSString?
let input = "http://test.com/blabla"
// Parse the string; might fail
let url : NSURL? = NSURL(string: input)
// Get the host part of the URL ("test.com")
let host = url?.host
// Split it up at the dots.
let hostParts = host?.componentsSeparatedByString(".")
// Assign the first part of the hostname if we were successful up to here.
if hostParts?.count > 0 {
result = hostParts![0]
}
Bonus: ignore "www":
if hostParts?.count > 0 {
if (hostParts![0] == "www" && hostParts!.count > 1) {
result = hostParts![1]
} else {
result = hostParts![0]
}
}
For swift 3.0:
let us = "http://example.com"
let range = us.range(of:"(?<=://)[^.]+(?=.com)", options:.regularExpression)
if range != nil {
let found = us.substring(with: range!)
print("found: \(found)") // found: example
}

Resources