I have an array like :
dateTime = ["2018/06/25 05:32:30","2018/05/25 02:37","2018/04/25 05:32:50","2018/07/25 06:30:30"]
Need to split the strings and get the response as :
time = ["05:32:30","02:37","05:32:50","06:30:30"]
Can anyone please help on this.
you can use flatMap:
let dates = ["2018/06/25 05:32:30","2018/05/25 02:37","2018/04/25 05:32:50","2018/07/25 06:30:30"]
let times = dates.flatMap({ $0.split(separator: " ").last ?? nil })
print(times)
// prints: ["05:32:30", "02:37", "05:32:50", "06:30:30"]
Use this below solution to get the times from all elements.
let dateTime = ["2018/06/25 05:32:30","2018/05/25 02:37","2018/04/25 05:32:50","2018/07/25 06:30:30"]
let array = dateTime.map { $0.components(separatedBy: " ")[1] }
//["05:32:30", "02:37", "05:32:50", "06:30:30"]
Loops each items & use split function
let times = dateTime.compactMap { $0.split(separator: " ").last }
Related
I know how to remove first character from a word in swift like this:
var data = "CITY Singapore"
data.removeFirst()
print(data)//ITY Singapore
what i want is to remove the first word and space so the result is "Singapore".
How can i remove the first word and leading space in swift?
You can try
let data = "CITY Singapore"
let res = data.components(separatedBy: " ").dropFirst().joined(separator: " ")
print(res)
Or
let res = data[data.range(of: " ")!.upperBound...] // may crash for no " " inside the string
Or you can go with this too
let strData = "CITY Singapore"
if let data = strData.components(separatedBy: " ").dropFirst().first {
// do with data
}
else {
// fallback
}
This is a Regular Expression solution, the benefit is to modify the string in place.
The pattern searches from the beginning of the string to the first space character
var data = "CITY Singapore"
if let range = data.range(of: "^\\S+\\s", options: .regularExpression) {
data.removeSubrange(range)
}
You can use String's enumerateSubstrings in range method (Foundation) using byWords option and remove the first enclosing range. You need also to stop enumeration after removing the range at the first occurrence:
var string = "CITY Singapore"
string.enumerateSubstrings(in: string.startIndex..., options: .byWords) { (_, _, enclosingRange, stop) in
string.removeSubrange(enclosingRange)
stop = true
}
string // "Singapore"
I have this string "01:07:30" and I would like to remove the zero in "01" and keep everything else the same. My final string should look like this
"1:07:30"
Is there a way to do so in Swift? Thank you so much!
Try the following. This will create a string, check to see if the first character is 0 if it is remove it. Otherwise do nothing.
var myString = "01:07:30"
if myString.first == "0" {
myString.remove(at: myString.startIndex)
}
print(myString) // 1:07:30
The final result is the string will now be 1:07:30 instead of 01:07:30.
If I'm best understanding your question, you want to replace the occurrences of "01" with "1" in your string, so you can use regex or the string functionality it self
simply:
let searchText = "01"
let replaceWithValue = "1"
let string = "01:07:08:00:01:01"
let newString = string.replacingOccurrences(of: searchText, with: replaceWithValue) // "1:07:08:00:1:1"
If you want to replace the fist occurrence only, simply follow this answer:
https://stackoverflow.com/a/33822186/3911553
If you just want to deal with string here is one of many solution:
var myString = "01:07:30"
let list = myString.components(separatedBy: ":")
var finalString = ""
for var obj in list{
if obj.first == "0" {
obj.removeFirst()
}
finalString += finalString.count == 0 ? "\(obj)" : ":\(obj)"
}
print(finalString)
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"
I have a string:
let mystring = "key=value=value=value=value"
When i did:
let ar = mystring.componentsSeparatedByString("=")
i get:
["key", "value", "value", "value", "value"]
but i need do split only once, like componentsSeparatedByString("=", 1), to get:
["key", "value=value=value=value"]
With Swift 2.1, you can use the split function as follows to do what you want:
let result = string.characters.split("=", maxSplit: 1, allowEmptySlices: true)
Some example code to test this would be:
let string = "key=value=value=value=value"
let result = string.characters.split("=", maxSplit: 1, allowEmptySlices: true)
print(String(result[0])) // "key"
print(String(result[1])) // "value=value=value=value"
This should do the job
func extract(rawData: String) -> [String]? {
let elms = rawData.characters.split("=", maxSplit: 1).map { String($0) }
guard let
key = elms.first,
value = elms.last
where elms.count == 2 else { return nil }
return [key, value]
}
Example:
let rawData = "key=value=value=value=value"
extract(rawData) // > ["key", "value=value=value=value"]
Please note the extract function does an optional array of strings. Infact if the input string does not contain at least an = then nil is returned.
The code has been tested with the Swift 2.1 and Xcode Playground 7.1.1.
Hope this helps.
You're probably going to have to write your own custom code to do that, using either NSScanner or rangeofString:options:range:
EDIT:
Actually, it sounds like the Swift String class's split function, with its maxSplit parameter, will do what you need. Take a look at the link in Preston's answer.
let mystring = "key=value=value=value=value"
let result = split(mystring as String, { $0 == "=" }, maxSplit: 1, allowEmptySlices: true)
result should now be [key, value=value=value=value]
Thanks for answers, i found working solution for swift2:
let mystring = "key=value=value=value=value"
mystring.characters.split(1, allowEmptySlices: true, isSeparator: { $0 == "=" }).map(String.init)
Try this: (tested and working in playground)
var key = str.substringToIndex(str.rangeOfString("=")!.startIndex)
var value = str.substringFromIndex(str.rangeOfString("=")!.startIndex.advancedBy(1))
var resultingArray = [key, value]
I'd like to add my dictionary with array in it to my arrayOfDictionary, i tried the suggested answer on this link, but it didn't work for me. I'm having problem on appending object in my dictionary.
Here's my code:
func formatADate() {
var dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.LongStyle
var journalDictionary = Dictionary<String, [Journal]>()
for index in 0..<self.sortedJournal.count {
let dateString = dateFormatter.stringFromDate(self.sortedJournal[index].journalDate)
var oldDateString = ""
// Split Date
var dateStringArr = split(dateString){$0 == " "}
var newDateString = "\(dateStringArr[0]) \(dateStringArr[2])"
// Append journal to corresponding dates
// journalDictionary[newDateString]? += [self.sortedJournal[index]]
// journalDictionary[newDateString]!.append(self.sortedJournal[index])
journalDictionary[newDateString]?.append(self.sortedJournal[index])
// add to array of journal
if !(newDateString == oldDateString) || (oldDateString == "") {
arrayOfJournalDictionary.append(journalDictionary)
}
}
println(arrayOfJournalDictionary)
}
With this line of code, it gives me empty object.
journalDictionary[newDateString]?.append(self.sortedJournal[index])
Any suggestion on how I can accomplish/fix this? I'm pretty amateur in Swift, so any help would be appreciated! Thank you.
Woah, date magic with string splits and stuff, yeiks. You already are using NSDateFormatters, for the wrong reasons though. Since journalDate is a date, use the formatter to give you the exact string you want from that date, dont let it give you some generic string and split and concatenate and argh... NOBODY will understand what you are trying to do there.
Back to the question:
Your journalDictionary is empty, if you write
journalDictionary[newDateString]?.append(self.sortedJournal[index])
You tell the program to read at "index" newDateString and if there is something take that and append a new value to it.
Do you see the mistake already?
if there is something -> You have no logic yet to insert the initial empty [Journal] for any given key.
At some point in your code you have to set up the array like so:
journalDictionary["myKey"] = []
Or probably more likely:
if journalDictionary[newDateString] == nil {
journalDictionary[newDateString] = [self.sortedJournal[index]]
} else {
journalDictionary[newDateString]?.append(self.sortedJournal[index])
}