Home:ALL Converter>How to get a substring from a specific character to the end of the string in swift 4?

How to get a substring from a specific character to the end of the string in swift 4?

Ask Time:2017-07-08T13:25:55         Author:Pangu

Json Formatter

I currently have a string containing a path to an image file like so:

/Users/user/Library/Developer/CoreSimulator/Devices/Hidden/data/Containers/Data/Application/Hidden/Documents/AppName/2017-07-07_21:14:52_0.jpeg

I'm trying to retrieve the full name of my image file like so: 2017-07-07_21:14:52_0.jpeg

How would I get the substring starting after the last / to the end of the file path?

I've seen questions related to using substrings:

  1. Swift: How to get substring from start to last index of character
  2. How does String substring work in Swift 3
  3. Substring from String in Swift

However, the provided answers did not help me with my specific problem.

I'm sure it may be something very simple, but all I keep getting is the wrong range of substrings.

Thanks!

Author:Pangu,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/44982840/how-to-get-a-substring-from-a-specific-character-to-the-end-of-the-string-in-swi
Martin R :

To answer your direct question: You can search for the last\noccurrence of a string and get the substring from that position:\n\nlet path = \"/Users/user/.../AppName/2017-07-07_21:14:52_0.jpeg\"\nif let r = path.range(of: \"/\", options: .backwards) {\n let imageName = String(path[r.upperBound...])\n print(imageName) // 2017-07-07_21:14:52_0.jpeg\n}\n\n\n(Code updated for Swift 4 and later.)\n\nBut what you really want is the \"last path component\" of a file path.\nURL has the appropriate method for that purpose:\n\nlet path = \"/Users/user/.../AppName/2017-07-07_21:14:52_0.jpeg\"\nlet imageName = URL(fileURLWithPath: path).lastPathComponent\nprint(imageName) // 2017-07-07_21:14:52_0.jpeg\n",
2017-07-08T05:33:27
yy