Confused
Confused

Reputation: 6278

Remove suffix from filename in Swift

When trying to remove the suffix from a filename, I'm only left with the suffix, which is exactly not what I want.

What (how many things) am I doing wrong here:

let myTextureAtlas = SKTextureAtlas(named: "demoArt")

let filename = (myTextureAtlas.textureNames.first?.characters.split{$0 == "."}.map(String.init)[1].replacingOccurrences(of: "\'", with: ""))! as String

print(filename)

This prints png which is the most dull part of the whole thing.

Upvotes: 21

Views: 25129

Answers (11)

ATV
ATV

Reputation: 4496

One liner:

let stringWithSuffixDropped = fileName.split(separator: ".").dropLast().joined(separator: ".")

Upvotes: 3

Wyetro
Wyetro

Reputation: 8578

You can also split the String using componentsSeparatedBy, like this:

let fileName = "demoArt.png"
var components = fileName.components(separatedBy: ".")
if components.count > 1 { // If there is a file extension
  components.removeLast()
  return components.joined(separator: ".")
} else {
  return fileName
}

To clarify:

fileName.components(separatedBy: ".")

will return an array made up of "demoArt" and "png".

Upvotes: 11

Jovan Stankovic
Jovan Stankovic

Reputation: 4751

If by suffix you mean path extension, there is a method for this:

let filename = "demoArt.png"
let name = (filename as NSString).deletingPathExtension
// name - "demoArt"

Upvotes: 43

Mikhail Medvedev
Mikhail Medvedev

Reputation: 37

You can return a new string removing a definite number of characters from the end.

   let fileName = "demoArt.png"
   fileName.dropLast(4)

This code returns "demoArt"

Upvotes: 2

possen
possen

Reputation: 9266

If you don't care what the extension is. This is a simple way.

let ss = filename.prefix(upTo: fileName.lastIndex { $0 == "." } ?? fileName.endIndex))

You may want to convert resulting substring to String after this. With String(ss)

Upvotes: 8

Laszlo
Laszlo

Reputation: 2778

How about using .dropLast(k) where k is the number of characters you drop from the suffix ?

Otherwise for removing extensions from path properly from filename, I insist you to use URL and .deletingPathExtension().lastPathComponent.

Maybe a bit overhead but at least it's a rock solid Apple API.

Upvotes: 5

Melany
Melany

Reputation: 466

let mp3Files = ["alarm.mp3", "bubbles.mp3", "fanfare.mp3"]
let ringtonsArray = mp3Files.flatMap { $0.components(separatedBy: ".").first }

Upvotes: 2

Ricardo Barroso
Ricardo Barroso

Reputation: 753

@Confused with Swift 4 you can do this:

let fileName = "demoArt.png"
// or on your specific case:
// let fileName = myTextureAtlas.textureNames.first

let name = String(fileName.split(separator: ".").first!)
print(name)

Additionally you should also unwrapp first but I didn't want to complicate the sample code to solve your problem.

Btw, since I've also needed this recently, if you want to remove a specific suffix you know in advance, you can do something like this:

let fileName = "demoArt.png"
let fileNameExtension = ".png"

if fileName.hasSuffix(fileNameExtension) {
    let name = fileName.prefix(fileName.count - fileNameExtension.count)
    print(name)
}

Upvotes: 6

Mecki
Mecki

Reputation: 132909

Some people here seem to overlook that a filename can have multiple periods in the name and in that case only the last period separates the file extension. So this.is.a.valid.image.filename.jpg and stripping the extension should return this.is.a.valid.image.filename and not this (as two answers here would produce) or anything else in between. The regex answer works correctly but using a regex for that is a bit overkill (probably 10 times slower than using simple string processing). Here's a generic function that works for everyone:

func stripFileExtension ( _ filename: String ) -> String {
    var components = filename.components(separatedBy: ".")
    guard components.count > 1 else { return filename }
    components.removeLast()
    return components.joined(separator: ".")
}

print("1: \(stripFileExtension("foo"))")
print("2: \(stripFileExtension("foo.bar"))")
print("3: \(stripFileExtension("foo.bar.foobar"))")

Output:

foo
foo
foo.bar

Upvotes: 14

CZ54
CZ54

Reputation: 5588

You can also use a Regexp to extract all the part before the last dot like that :

let fileName = "test.png"
let pattern  = "^(.*)(\\.[a-zA-Z]+)$"
let regexp = try! NSRegularExpression(pattern: pattern, options: [])
let extractedName = regexp.stringByReplacingMatches(in: fileName, options: [], range: NSMakeRange(0, fileName.characters.count), withTemplate: "$1")
print(extractedName) //test

Upvotes: 2

Nirav D
Nirav D

Reputation: 72410

In iOS Array start with 0 and you want name of the file without extension, so you have split the string using ., now the name will store in first object and extension in the second one.

Simple Example

let fileName = "demoArt.png"
let name = fileName.characters.split(".").map(String.init).first

Upvotes: 8

Related Questions