20

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.

5
  • Use first object map(String.init)[0] pass subscript 0 instead of 1, or use first? directly map(String.init).first?
    – Nirav D
    Commented Oct 6, 2016 at 4:53
  • What is this doing differently?
    – Confused
    Commented Oct 6, 2016 at 5:01
  • Can you explain "What is this doing differently?"
    – Nirav D
    Commented Oct 6, 2016 at 5:04
  • Exactly; can you explain how it is that the change you're suggesting actually works?
    – Confused
    Commented Oct 6, 2016 at 5:06
  • btw I copied this line. I have very little idea what it's doing, or how it could possibly split a string.
    – Confused
    Commented Oct 6, 2016 at 5:06

11 Answers 11

43

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"
14

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
11

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".

5
  • 1
    I just got this one working in a loop. VERY COOL! This function and its syntax is (to my eyes) much easier to understand, look at and incorporate. Very, VERY cool!
    – Confused
    Commented Oct 6, 2016 at 20:42
  • @Confused, glad it worked for you! Yeah I think it's the simplest way to do this.
    – Wyetro
    Commented Oct 6, 2016 at 21:21
  • I like this very much. Simple, concise, Commented Jul 18, 2017 at 12:04
  • @BartvanKuik, I'd also look at Nirav D's answer below - it doesn't have the same force unwrap as mine.
    – Wyetro
    Commented Jul 18, 2017 at 14:12
  • 1
    This doesn't work if the file name itself also contains periods.
    – Greg Brown
    Commented Sep 19, 2017 at 14:13
8

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
7
  • argh, so this is a very powerful little piece of code, splitting and storing the name, first part in position[0], second part in position [1]. What's the name of this array? map?
    – Confused
    Commented Oct 6, 2016 at 5:23
  • 1
    split(".") returns character View and using map function we have created String from it, if you don't use .first then name will be array with two objects.
    – Nirav D
    Commented Oct 6, 2016 at 5:25
  • ¿Why does your line not need the very confusing: $0==
    – Confused
    Commented Oct 6, 2016 at 6:07
  • @Confused characters will use to iterate through the all the characters of string one by one, if you write .split { $0 == "." }, here $0, iterate one by one characters of string and check for . but you can also directly use split function like split(".").
    – Nirav D
    Commented Oct 6, 2016 at 6:15
  • @Confused Also the syntax you are using is used split with closure and i have used it split() function.
    – Nirav D
    Commented Oct 6, 2016 at 6:26
8

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)

4
  • how does this work? Sorry. I'm a little dense, and need explanations.
    – Confused
    Commented Apr 20, 2018 at 12:23
  • 1
    Sorry there was a slight issue with my original code, hopefully the change I made will help understanding. To explain, the prefix function searches a collection, in this case a string, until it finds one matching the character, it returns a substring with all those characters prior to the matched character. The String( calls the constructor converting the substring to a regular string.
    – possen
    Commented Apr 20, 2018 at 19:05
  • If you have asd.asd/asd.es this is a bad answer. Commented Apr 11, 2019 at 10:38
  • OK fixed it to handle the case presented by Ariel.
    – possen
    Commented Apr 15, 2019 at 20:12
6

@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)
}
1
  • 1
    @Moritz, yeah. I did add it because I was getting a warning here, probably because I started with different code. It's fixed now, thanks. Commented Dec 7, 2017 at 19:31
5

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.

3

One liner:

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

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
1
  • Strewth. Way beyond my stringFu, but very cool to know. I'm sure I'll need it quite soon... THANK YOU!
    – Confused
    Commented Oct 6, 2016 at 21:03
2
let mp3Files = ["alarm.mp3", "bubbles.mp3", "fanfare.mp3"]
let ringtonsArray = mp3Files.flatMap { $0.components(separatedBy: ".").first }
1
  • 2
    now imagine a "my.file.mp3". Your algorithm, will return "my".
    – zaitsman
    Commented Jul 8, 2020 at 2:52
2

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"

3
  • 1
    Now imagine you have a .gz file. Or a .plan file...
    – ATV
    Commented Mar 26, 2022 at 16:42
  • I would suggest to always avoid hard-coded stuff like this...
    – mārt1cz
    Commented Mar 6, 2023 at 6:46
  • 1
    I was young and naive Commented Mar 7, 2023 at 7:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.