Xcode 用Swift处理字符串
我想用Swift把一根绳子分开。我有以下字符串Xcode 用Swift处理字符串,xcode,macos,swift2,Xcode,Macos,Swift2,我想用Swift把一根绳子分开。我有以下字符串 Program-/path/to/file.doc 我想从这个字符串中得到三个信息 程序 /path/to/file.doc file.doc 我从以下解决方案开始 var str = "Program - /path/to/file.doc" let indi = str.rangeOfString("-")?.startIndex let subString = str.substringWithRange(Range<String.I
Program-/path/to/file.doc
我想从这个字符串中得到三个信息
程序
/path/to/file.doc
file.doc
我从以下解决方案开始
var str = "Program - /path/to/file.doc"
let indi = str.rangeOfString("-")?.startIndex
let subString = str.substringWithRange(Range<String.Index>(start: str.startIndex, end: indi!))
let subString2 = str.substringWithRange(Range<String.Index>(start: indi!, end: str.endIndex))
var str=“程序-/path/to/file.doc”
设indi=str.rangeOfString(“-”)?startIndex
让subString=str.substringWithRange(Range(开始:str.startIndex,结束:indi!))
让subString2=str.substringWithRange(Range(开始:indi!,结束:str.endIndex))
这给了我结果
“程序”
和
“-/path/to/file.doc”
但是,在最后一次/
之后,如何获取file.doc
如何增加/减少和范围索引以避免空格?是的,sidyll的建议是正确的,通过将Unix path转换为NSURL来获取组件是一种非常常见的做法。您可能想写以下内容:
var str=“程序-/path/to/file.doc”
如果让indi=str.rangeOfString(“-”)?startIndex{
让subString=str.substringWithRange(Range(开始:str.startIndex,结束:indi))
让subString2=str.substringWithRange(Range(开始:indi,结束:str.endIndex))
让fileName=NSURL(字符串:subString2).lastPathComponent()
}
我强烈建议你不要这样强行展开。考虑这种情况,如果该代码将与没有特定模式的字符串一起工作,例如空字符串。正确,运行时错误。不幸的是,我不知道Swift如何回答您的问题,但在objective-c中,我首先使用
组件从该字符串中获取一个数组,该字符串由字符串@“-”分隔。然后,元素0是您的名称,1是路径。使用[[NSURL urlWithString:[array lastObject]]lastPathComponent]
获取该文件名。非常好,感谢您发送此代码。还有关于格式和安全性的重要建议。稍微简化(来自原始代码):您不需要范围(开始:x,结束:y)
。所有这些都相当于x。。
var str = "Program - /path/to/file.doc"
if let indi = str.rangeOfString(" - ")?.startIndex {
let subString = str.substringWithRange(Range<String.Index>(start: str.startIndex, end: indi))
let subString2 = str.substringWithRange(Range<String.Index>(start: indi, end: str.endIndex))
let fileName = NSURL(string: subString2).lastPathComponent()
}