如何在Swift 4中获取从特定字符到字符串结尾的子字符串? [英] How to get a substring from a specific character to the end of the string in swift 4?

查看:180
本文介绍了如何在Swift 4中获取从特定字符到字符串结尾的子字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个包含图像文件路径的字符串,如下所示:

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

我正在尝试检索图像文件的全名,如下所示: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:如何获取从字符的开始到最后一个索引的子字符串
  2. String子字符串如何在Swift 3中工作
  3. Swift中String的子字符串
  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.

谢谢!

推荐答案

要回答您的直接问题:您可以搜索最后一个 出现一个字符串并从该位置获取子字符串:

To answer your direct question: You can search for the last occurrence of a string and get the substring from that position:

let path = "/Users/user/.../AppName/2017-07-07_21:14:52_0.jpeg"
if let r = path.range(of: "/", options: .backwards) {
    let imageName = String(path[r.upperBound...])
    print(imageName)  // 2017-07-07_21:14:52_0.jpeg
}

(为Swift 4及更高版本更新了代码.)

(Code updated for Swift 4 and later.)

但是您真正想要的是文件路径的最后路径组件". URL具有用于此目的的适当方法:

But what you really want is the "last path component" of a file path. URL has the appropriate method for that purpose:

let path = "/Users/user/.../AppName/2017-07-07_21:14:52_0.jpeg"
let imageName = URL(fileURLWithPath: path).lastPathComponent
print(imageName) // 2017-07-07_21:14:52_0.jpeg

这篇关于如何在Swift 4中获取从特定字符到字符串结尾的子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆