How to get data from string after particular backslash? - ios

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"

Related

Get correct parameter value from URL in "/:id=" format using regex

What is the best way to get the id value from this url:
URL(string: "urlScheme://search/:id=0001")
I've been trying to route this URL using a deep link request. However, my url routing solution JLRoutes shows the parameters as key = id and value = :id=0001.
I instead need the parameters to be key = id and value = "0001".
In an ideal world I would just be using a URL string like "urlScheme://search/0001" and not have any problem but the ":id=" part has to be in there. George's comment about converting the parameter to a URL in of itself and using .pathComponents.last does work, but I think a regex solution is probably going to scale better going forward.
The answer from #George should work fine, but two things struck me: you decided you wanted a regex solution, and to make this generic seemed to be asking for a recursive solution.
The below approach uses regex to identify up to the last /: delimiter, then has to do a bit of inelegant string handling to split it into the base string and the final pair of (key: value) params. I'd hoped to be able to write a regex that just matches those final parameters as that would be a far cleaner range to work with, but haven't managed it yet!
func paramsFrom(_ str: String) -> [String: String] {
guard let baseRange = str.range(of:#"^.+\/:"#, options: .regularExpression ) else { return [:] }
let base = String(str[baseRange].dropLast(2))
let params = str.replacingCharacters(in: baseRange, with: "").components(separatedBy: "=")
return [params.first! : params.last!].merging(paramsFrom(base)){(current, _) in current}
}
using this on your example string returns:
["id": "0001", "title": "256", "count": "100"]
EDIT:
Managed to dig out the old regex brain cells and match just the final pair of parameters. You could adapt the above to use the regex
(?<=\/:)[a-zA-Z0-9=]+$
and the have slightly cleaner string handling as the shortened base string becomes
String(str.dropLast(str[paramsRange].count))
If your URL is in the form of an actual URL query, e.g. urlScheme://search?id=0001, there is a nice way to do this.
With thanks to vadian, this is really simple. You can just do the following:
let components = URLComponents(string: "urlScheme://search?id=0001&a=2")!
let dict = components.queryItems?.reduce(into: [:]) { partialResult, queryItem in
partialResult[queryItem.name] = queryItem.value
}
Or a slightly more compact version for dict:
let dict = components.queryItems?.reduce(into: [:], { $0[$1.name] = $1.value })
Result from given input:
["id": "0001", "a": "2"]
If you must use the current URL form
You can replace the URL string, such as:
let urlStr = "urlScheme://search/:id=0001/:a=2"
let comps = urlStr.components(separatedBy: "/:")
let newUrl: String
if comps.count > 1 {
newUrl = "\(comps.first!)?\(comps.dropFirst().joined(separator: "&"))"
} else {
newUrl = urlStr
}
print(newUrl)
Prints: urlScheme://search?id=0001&a=2
Original answer (slightly modified)
If you have a URL with queries separated by /: you can use the following:
// Example with multiple queries
let url = URL(string: "urlScheme://search/:id=0001/:a=2")!
let queries = url.lastPathComponent.dropFirst().split(separator: "/:")
var dict = [String: String]()
for query in queries {
let splitQuery = query.split(separator: "=")
guard splitQuery.count == 2 else { continue }
let key = String(splitQuery.first!)
let value = String(splitQuery[1])
dict[key] = value
}
print(dict)
Result is same as before.
You can use next regex approach to enumerate parameters in your url path:
let urlString = "urlScheme://search/:id=0001" as NSString
let regex = try! NSRegularExpression(pattern: "([^:\\/]+)=([0-9]+)")
if let match = regex.matches(in: urlString as String, options: [], range: NSMakeRange(0, urlString.length)).first, match.numberOfRanges == 3 {
let key = urlString.substring(with: match.range(at: 1))
let value = urlString.substring(with: match.range(at: 2))
print(key, ":", value)
}
// Prints
id : 0001

How to separate two URLs in a String in Swift?

What is the best way to split this String into two using Swift?
"https://apod.nasa.gov/apod/http://nusoft.fnal.gov/nova/public/img/FD-evt-echo.gif"
I only need the second part of url in the String. In this example, in this case I just need:
"http://nusoft.fnal.gov/nova/public/img/FD-evt-echo.gif"
let str = "https://apod.nasa.gov/apod/http://nusoft.fnal.gov/nova/public/img/FD-evt-echo.gif"
if let lastStr = str.components(separatedBy: "http").last
{
let result = "http" + lastStr
print(result)
}
Console Output: http://nusoft.fnal.gov/nova/public/img/FD-evt-echo.gif

How to append an array in URL request type GET in Swift?

I am using Xcode7.3 with Swift2.2.
I want to append an Array in url request.For example my array like
[“jeevan”,”jeejo”]. I want to append this array with key(arrayKey) in url request like must be the following pattern
https://api.com/pre/ws/ch/roo?arrayKey=jeevan%2Cjeejo
How to solve this issue? Please help me
You need to use encode your URL instead of join Array with separator, but if you want to merge Array with URL you can try like this.
let str = ["jeevan","jeejo"]
let join = str.joinWithSeparator("%2C")
let url = "https://api.com/pre/ws/ch/roo?arrayKey=\(join)"
If you want to encode url encode this way.
let str = ["jeevan","jeejo"]
let join = str.joinWithSeparator(",")
let url = "https://api.com/pre/ws/ch/roo?arrayKey=\(join)"
let encoded = url.stringByAddingPercentEncodingWithAllowedCharacters(.URLFragmentAllowedCharacterSet())
Note : The reason I have used , is because %2C is encode for , you can confirm it here on W3School URL Encoding.
easy solution can be like this
var URIString = ""
for item in array {
URIString +=\(item)%2C
}
after subtract last 3 characters and make URL string
Simple code like this
var array: [String] = ["jeevan","jeejo"]
var myString = ""
for i in 0..<array.count {
myString += array[i]
if (i+1)<array.count { mystring+="%2C" }
}
Can give you result like this:
jeevan%2Cjeejo

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

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

How to get the filename from the filepath in swift

How to get the filename from the given file path string?
For example if I have a filepath string as
file:///Users/DeveloperTeam/Library/Developer/CoreSimulator/Devices/F33222DF-D8F0-448B-A127-C5B03C64D0DC/data/Containers/Data/Application/5D0A6264-6007-4E69-A63B-D77868EA1807/tmp/trim.D152E6EA-D19D-4E3F-8110-6EACB2833CE3.MOV
and I would like to get the return result as
trim.D152E6EA-D19D-4E3F-8110-6EACB2833CE3.MOV
Objective C
NSString* theFileName = [string lastPathComponent]
Swift
let theFileName = (string as NSString).lastPathComponent
SWIFT 3.x or SWIFT 4:
Shortest and cleanest way of doing this is below. In this example url variable is type of URL in this way we can have a human readable String result of the full file name with extension like My file name.txt and Not like My%20file%20name.txt
// Result like: My file name.txt
let fileName = url.lastPathComponent
If you want to get the current file name such as for logging purposes, I use this.
Swift 4
URL(fileURLWithPath: #file).lastPathComponent
Swift 2:
var file_name = NSURL(fileURLWithPath: path_to_file).lastPathComponent!
let theURL = URL(string: "yourURL/somePDF.pdf") //use your URL
let fileNameWithExt = theURL?.lastPathComponent //somePDF.pdf
let fileNameLessExt = theURL?.deletingPathExtension().lastPathComponent //somePDF
In order for this to work your url must be of type URL not a string so don't convert it to a string before hand.
You can copy and paste this code directly into playground to see how it works.
Try this
let filename: String = "your file name"
let pathExtention = filename.pathExtension
let pathPrefix = filename.stringByDeletingPathExtension
Updated :
extension String {
var fileURL: URL {
return URL(fileURLWithPath: self)
}
var pathExtension: String {
return fileURL.pathExtension
}
var lastPathComponent: String {
return fileURL.lastPathComponent
}
}
Hope it helps.
Below code is working for me in Swift 4.X
let filename = (self.pdfURL as NSString).lastPathComponent // pdfURL is your file url
let fileExtention = (filename as NSString).pathExtension // get your file extension
let pathPrefix = (filename as NSString).deletingPathExtension // File name without extension
self.lblFileName.text = pathPrefix // Print name on Label
You can pass the url in fileUrl, like I did below:-
let fileUrl: String = "https://www.himgs.com/imagenes/hello/social/hello-fb-logo.png" // Pass the URL
let lastPathComponent = URL.init(string: fileUrl)?.lastPathComponent ?? "" // With this you will get last path component
let fileNameWithExtension = lastPathComponent
//This last path component will provide you file Name with extension.
I've done some performance tests (iOS 14, real device, release configuration):
(#file as NSString).lastPathComponent // The fastest option.
URL(string: #file)!.lastPathComponent // 2.5 times slower than NSString.
#file.components(separatedBy: "/").last! // 7 times slower than NSString.
Bonus:
URL(fileURLWithPath: #file, isDirectory: false).lastPathComponent // About the same as URL(string:).
URL(fileURLWithPath: #file).lastPathComponent // 2.5 times slower than with explicit isDirectory.
Swift 5. This one works faster than both URL and NSString options:
path.components(separatedBy: "/").last
To retrieve filename without its extension from a URL in Swift >= 4.2:
let urlWithoutFileExtension: URL = originalFileUrl.deletingPathExtension()
let fileNameWithoutExtension: String = urlWithoutFileExtension.lastPathComponent
Creates unique "file name" form url including two previous folders
func createFileNameFromURL (colorUrl: URL) -> String {
var arrayFolders = colorUrl.pathComponents
// -3 because last element from url is "file name" and 2 previous are folders on server
let indx = arrayFolders.count - 3
var fileName = ""
switch indx{
case 0...:
fileName = arrayFolders[indx] + arrayFolders[indx+1] + arrayFolders[indx+2]
case -1:
fileName = arrayFolders[indx+1] + arrayFolders[indx+2]
case -2:
fileName = arrayFolders[indx+2]
default:
break
}
return fileName
}

Resources