获取字符串中最后一个char-type之后的文本

时间:2017-07-26 12:54:56

标签: ios swift3 nsstring

我有以下字符串类型:

def flattenDf(df: DataFrame): DataFrame = { var end = false var i = 0 val fields = df.schema.fields val fieldNames = fields.map(f => f.name) val fieldsNumber = fields.length while (!end) { val field = fields(i) val fieldName = field.name field.dataType match { case st: StructType => val childFieldNames = st.fieldNames.map(n => fieldName + "." + n) val newFieldNames = fieldNames.filter(_ != fieldName) ++ childFieldNames val newDf = df.selectExpr(newFieldNames: _*) return flattenDf(newDf) case at: ArrayType => val fieldNamesExcludingArray = fieldNames.filter(_ != fieldName) val fieldNamesAndExplode = fieldNamesExcludingArray ++ Array(s"explode($fieldName) as a") val fieldNamesToSelect = fieldNamesExcludingArray ++ Array("a.*") val explodedDf = df.selectExpr(fieldNamesAndExplode: _*) val explodedAndSelectedDf = explodedDf.selectExpr(fieldNamesToSelect: _*) return flattenDf(explodedAndSelectedDf) case _ => Unit } i += 1 end = i >= fieldsNumber } df }

我需要访问文件扩展名,在本例中为file:///private/var/mobile/Containers/Data/Application/1C02189F-2426-4420-A178-1CC420CBBD3A/tmp/com.test.Test-Inbox/2015-04-23_00002.jpg

我想在最后.jpg之后访问该字符串,因为它始终是我想要的文件扩展名,但是我无法将其子串到最后3个字符,因为扩展名可能有4个字符,如{{1} }或.

最好的方法是什么?

我认为反过来字符串并通过char循环char以获取最新的(在这种情况下是第一个).docx然后当我找到长度时我可以将其子串。

有什么想法吗?

由于

5 个答案:

答案 0 :(得分:2)

Swift3 中,您只能从路径轻松获取。不需要做任何额外的事情。

let filePath:NSString = "the_file_name.png"
let fileExtension = filePath.pathExtension

答案 1 :(得分:1)

您可以使用String.components(separatedBy:)String分隔为由特定字符分隔的子字符串("。" 在您的情况下)。由于您知道文件扩展名将位于最后一个分隔符之后,因此您只需在子串数组上调用.last即可访问它。

let fileNameWithExtension = "file:///private/var/mobile/Containers/Data/Application/1C02189F-2426-4420-A178-1CC420CBBD3A/tmp/com.test.Test-Inbox/2015-04-23_00002.jpg"
let fileExtension = fileNameWithExtension.components(separatedBy: ".").last

答案 2 :(得分:1)

你可以简单地使用它。

let string = "file:///private/var/mobile/Containers/Data/Application/1C02189F-2426-4420-A178-1CC420CBBD3A/tmp/com.test.Test-Inbox/2015-04-23_00002.jpg"
let all = string.components(separatedBy: ".")
let ext = all.last
print(ext)

答案 3 :(得分:1)

你可以通过

获得它
NSURL *stringFilePath = [NSURL URLWithString:@"file:///private/var/mobile/Containers/Data/Application/1C02189F-2426-4420-A178-1CC420CBBD3A/tmp/com.test.Test-Inbox/2015-04-23_00002.jpg"];

NSString *fileName = [stringFilePath lastPathComponent];

获得扩展

NSLog(@"%@", fileName.pathExtension)

对于Swift:

let stringFilePath:NSString = "file:///private/var/mobile/Containers/Data/Application/1C02189F-2426-4420-A178-1CC420CBBD3A/tmp/com.test.Test-Inbox/2015-04-23_00002.jpg"
let strFileExtenson = stringFilePath.pathExtension
print(strFileExtenson)

答案 4 :(得分:0)

试试这个:

let fileNameWithExtension = "file:///private/var/mobile/Containers/Data/Application/1C02189F-2426-4420-A178-1CC420CBBD3A/tmp/com.test.Test-Inbox/2015-04-23_00002.jpg"
let url = URL(string:fileNameWithExtension)
print(url?.pathExtension ?? "")